home *** CD-ROM | disk | FTP | other *** search
/ Mac Magazin/MacEasy 21 / Mac Magazin and MacEasy Magazine CD - Issue 21.iso / Wissenschaft & Technik / yorick12vr1-ppc folder / startup / std.i < prev    next >
Text File  |  1996-02-07  |  115KB  |  2,857 lines

  1. /*
  2.     STD.I
  3.     Declarations of standard Yorick functions.
  4.  
  5.     $Id: std.i,v 1.1 1993/08/27 18:32:09 munro Exp munro $
  6.  
  7.     The Codger automatic code generator program uses this file to
  8.     generate appropriate C code to initialize the various built-in
  9.     functions declared here.
  10.     This file is also used as online documentation for these functions
  11.     by Yorick's help mechanism.
  12.  
  13.     The "extern" declaration of each function or variable is a no-op,
  14.     but causes Yorick to place the variable in the sourceList for this
  15.     include file, making it available for online help.  The DOCUMENT
  16.     comment is provided in a standard format to simplify manipulation
  17.     of such comments by programs other than Yorick;  it should immediately
  18.     follow the corresponding "extern" so that it will be visible when
  19.     the page containing the "extern" is displayed.
  20.  
  21.     The Codger code generator finds each "extern" line and creates
  22.     initialization code binding the associated Yorick variable to
  23.     either a BuiltIn function (see ydata.h) Y_variable, or, if a
  24.     "reshape, variable, ..." declaration is found, to a global
  25.     compiled variable y_variable with the compiled data type
  26.     corresponding to the Yorick data type mentioned in the "reshape"
  27.     command.  Codger can generate certain simple Y_variable wrapper
  28.     routines if further information is provided in a PROTOTYPE comment.
  29.  */
  30. /*    Copyright (c) 1994.  The Regents of the University of California.
  31.                     All rights reserved.  */
  32.  
  33. extern help;
  34. /* DOCUMENT help, topic
  35.          or help
  36.      Prints DOCUMENT comment from include file in which the variable
  37.      TOPIC was defined, followed by the line number and filename.
  38.      By opening the file with a text editor, you may be able to find
  39.      out more, especially if no DOCUMENT comment was found.
  40.      Examples:
  41.        help, set_path
  42.      prints the documentation for the set_path function.
  43.        help
  44.      prints the DOCUMENT comment you are reading.
  45.  
  46.      This copy of Yorick was launched from the directory:
  47.      **** Y_LAUNCH (computed at runtime) ****
  48.      Yorick's "site directory" at this site is:
  49.      **** Y_SITE (computed at runtime) ****
  50.      You can find out a great deal more about Yorick by browsing
  51.      through these directories.  Begin with the site directory,
  52.      and pay careful attention to the subdirectories doc/ (which
  53.      contains documentation relating to Yorick), and include/ and
  54.      contrib/ (which contain many examples of Yorick programs).
  55.      Look for files called README (or something similar) in any
  56.      of these directories -- they are intended to assist browsers.
  57.      The site directory itself contains std.i and graph.i, which
  58.      are worth reading.
  59.  
  60.      Type:
  61.        help, dbexit
  62.      for help on debug mode.  If your prompt is "dbug>" instead of
  63.      ">", dbexit will return you to normal mode.
  64.  
  65.    SEE ALSO: info, print, copyright, warranty, legal
  66.  */
  67.  
  68. local copyright, warranty;
  69. /* DOCUMENT copyright, (no) warranty
  70.  
  71.      Copyright (c) 1995.  The Regents of the University of California.
  72.                    All rights reserved.
  73.  
  74.      Yorick is provided "as is" without any warranty, either expressed or
  75.      implied.  For a complete statement, type:
  76.  
  77.         legal
  78.  
  79.      at the Yorick prompt.
  80.  
  81.    SEE ALSO: legal
  82.  */
  83.  
  84. func legal(void)
  85. /* DOCUMENT legal
  86.      Prints the legal details of Yorick's copyright, licensing,
  87.      and lack of warranty.
  88.    SEE ALSO: copyright, warranty
  89.  */
  90. {
  91.   require, "legal.i";
  92.   raw_legal;
  93. }
  94.  
  95. func help_worker
  96. /* xxDOCUMENT help_worker (Not for interactive use -- called by help.)
  97.  */
  98. {
  99.   /* help_worker task is pushed by help function -- topic and file
  100.      arguments are left in help_topic and help_file variables */
  101.   topic= help_topic;   help_topic= [];
  102.   file= help_file;     help_file= [];
  103.  
  104.   if (file) {
  105.     mark= bookmark(file);
  106.     line= rdline(file);
  107.  
  108.     if (typeof(topic)!="struct_definition") {
  109.       /* non-struct looks for DOCUMENT comment before any blank lines */
  110.       n= 10;   /* read at most 10 lines looking for DOCUMENT comment */
  111.       while (strtok(line)(1) && n--) {
  112.     if (strmatch(line, "/* DOCUMENT")) break;
  113.     line= rdline(file);
  114.       }
  115.       if (strmatch(line, "/* DOCUMENT")) {
  116.     do {
  117.       if (strmatch(line, "**** Y_LAUNCH (computed at runtime) ****"))
  118.         write, "      "+Y_LAUNCH;
  119.       else if (strmatch(line, "**** Y_SITE (computed at runtime) ****"))
  120.         write, "      "+Y_SITE;
  121.       else
  122.         write, line;
  123.       line= rdline(file);
  124.       if (!line) break;
  125.     } while (!strmatch(line, "*/"));
  126.     write, line;
  127.       } else {
  128.     write, "<DOCUMENT comment not found>";
  129.       }
  130.  
  131.     } else {
  132.       /* struct just prints definition */
  133.       gotopen= 0;
  134.       do {
  135.     if (!gotopen) gotopen= strmatch(line, "{");
  136.     write, line;
  137.     if (gotopen && strmatch(line, "}")) break;
  138.       } while (line= rdline(file));
  139.     }
  140.  
  141.     write, "defined at:"+print(mark)(2);
  142.  
  143.   } else {
  144.     write, "<not defined in an include file, running info function>";
  145.     info, topic;
  146.   }
  147. }
  148.  
  149. func info(topic)
  150. /* DOCUMENT info, expr
  151.      prints the data type and array dimensions of EXPR.
  152.    SEE ALSO: help, print
  153.  */
  154. {
  155.   if (is_array(topic)) {
  156.     void= use_origins(1);  /* assure NON-forced origin */
  157.     line= "array(" + nameof(structof(topic));
  158.     dims= dimsof(topic);
  159.     orgs= orgsof(topic);
  160.     ndims= dims(1)+1;
  161.     for (i=2 ; i<=ndims ; i++) {
  162.       line+= ",";
  163.       if (orgs(i)!=1)
  164.     line+= print(orgs(i))(1)+":"+print(orgs(i)+dims(i)-1)(1);
  165.       else
  166.     line+= print(dims(i))(1);
  167.     }
  168.     line+= ")";
  169.     write, line;
  170.   } else {
  171.     print, topic;
  172.   }
  173. }
  174.  
  175. /*--------------------------------------------------------------------------*/
  176.  
  177. extern quit;
  178. /* DOCUMENT quit
  179.      Exit YMainLoop when current task finishes.
  180.      Normally this terminates the program.
  181.  */
  182.  
  183. extern system;
  184. /* DOCUMENT system, "shell command line"
  185.      Passes the command line string to a shell for execution.
  186.      If the string is constant, you may use the special syntax:
  187.          $shell command line
  188.      (A long command line may be continued by ending the line with \
  189.      as usual.)  The system function syntax allows Yorick to compute
  190.      parts of the command line string, while the simple $ escape
  191.      syntax does not.  In either case, the only way to get output
  192.      back from such a command is to redirect it to a file, then
  193.      read the file.  Note that Yorick does not regain control
  194.      until the subordinate shell finishes.  (Yorick will get control
  195.      back if the command line backgrounds the job.)
  196.  */
  197.  
  198. extern yorick_init;
  199. /* xxDOCUMENT yorick_init
  200.      Re-initializes all of the built-in functions for this version
  201.      of Yorick.  To be used in desperation if you overwrite some
  202.      critical built-in function by mistake.  Of course, if you
  203.      redefine yorick_init, you won't be able to recover anything.
  204.  */
  205.  
  206. extern set_path;
  207. /* DOCUMENT set_path, "dir1:dir2:dir3:..."
  208.          or set_path
  209.      sets the include file search path to the specified list of
  210.      directories.  The specified directories are searched left to
  211.      right for include files specified as relative file names in
  212.      #include directives, or to the include or require functions.
  213.      If the argument is omitted, restores the default search path,
  214.      ".:~/Yorick:Y_LAUNCH/include:Y_SITE/include:Y_SITE/contrib",
  215.      where y_site is the main Yorick directory for this site.
  216.      The Y_LAUNCH directory is the directory which contains the
  217.      executable; this directory is omitted if it is the same as
  218.      Y_SITE.
  219.  
  220.      Only the "end user" should ever call set_path, and then only in
  221.      his or her custom.i file, for the purpose of placing a more
  222.      elaborate set of personal directories containing Yorick procedures.
  223.      For example, if someone else maintains Yorick code you use, you
  224.      might put their ~/Yorick on your include path.
  225.  
  226.    SEE ALSO: Y_LAUNCH, Y_SITE, include, require
  227.  */
  228.  
  229. extern set_site;
  230. /* xxDOCUMENT set_site, site_directory
  231.      sets Y_LAUNCH, Y_SITE as a side effect.  Should only be called from
  232.      paths.i, and is never called by default.  See paths.i.  */
  233.  
  234. extern yorick_stats;
  235. /* DOCUMENT yorick_stats
  236.      returns an array of longs describing Yorick memory usage.
  237.      For debugging.  See ydata.c source code.
  238.  */
  239.  
  240. extern disassemble;
  241. /* DOCUMENT disassemble(function)
  242.          or disassemble, function
  243.      Disassembles the specified function.  If called as a function, the
  244.      result is returned as a vector of strings; if called as a subroutine,
  245.      the disassembly is printed at the terminal.  If the function is nil,
  246.      the current *main* program is disassembled -- you must include the
  247.      call to disassemble in the main program, of course, NOT on its own
  248.      line as a separate main program.
  249.  */
  250.  
  251. extern reshape;
  252. /* DOCUMENT reshape, reference, address, type, dimension_list
  253.          or reshape, reference, type, dimension_list
  254.          or reshape, reference
  255.      The REFERENCE must be an unadorned variable, not an expression;
  256.      reshape sets this variable to an LValue at the specified ADDRESS
  257.      with the specified TYPE and DIMENSION_LIST.  (See the array
  258.      function documentation for acceptable DIMENSION_LIST formats.)
  259.      If ADDRESS is an integer (e.g.- a long), the programmer is
  260.      responsible for assuring that the data at ADDRESS is valid.
  261.      If ADDRESS is a (Yorick) pointer, Yorick will assure that the
  262.      data pointed to will not be discarded, and the reshape will
  263.      fail if TYPE and DIMENSION_LIST extend beyond the pointee
  264.      bounds.  In the second form, ADDRESS is taken to be &REFERENCE;
  265.      that is, the TYPE and DIMENSION_LIST of the variable are changed
  266.      without doing any type conversion.  In the third form, REFERENCE
  267.      is set to nil ([]).  (Simple redefinition will not work on a
  268.      variable defined using reshape.)
  269.   SEE ALSO: array, dimsof, numberof, is_array
  270.  */
  271.  
  272. /*--------------------------------------------------------------------------*/
  273.  
  274. extern array;
  275. /* DOCUMENT array(value, dimension_list)
  276.          or array(type, dimension_list)
  277.      returns an object of the same type as VALUE, consisting of copies
  278.      of VALUE, with the given DIMENSION_LIST appended to the dimensions
  279.      of VALUE.  Hence, array(1.5, 3, 1) is the same as [[1.5, 1.5, 1.5]].
  280.      In the second form, the VALUE is taken as scalar zero of the TYPE.
  281.      Hence, array(short, 2, 3) is the same as [[0s,0s],[0s,0s],[0s,0s]].
  282.      A DIMENSION_LIST is a list of arguments, each of which may be
  283.      any of the following:
  284.         (1) A positive scalar integer expression,
  285.     (2) An index range with no step field (e.g.-  1:10), or
  286.     (3) A vector of integers [number of dims, length1, length2, ...]
  287.         (that is, the format returned by the dimsof function).
  288.   SEE ALSO: reshape, is_array, dimsof, numberof, grow, span, use_origins,
  289.             _lst
  290.  */
  291.  
  292. /*--------------------------------------------------------------------------*/
  293.  
  294. extern structof;
  295. /* DOCUMENT structof(object)
  296.      returns the data type of OBJECT, or nil for non-array OBJECTs.
  297.      Use typeof(object) to get the ASCII name of a the data type.
  298.   SEE ALSO: typeof, dimsof, numberof, sizeof, nameof
  299.  */
  300.  
  301. extern dimsof;
  302. /* DOCUMENT dimsof(object)
  303.          or dimsof(object1, object2, ...)
  304.      returns a vector of integers describing the dimensions of OBJECT.
  305.      The format of the vector is [number of dims, length1, length2, ...].
  306.      The orgsof function returns the origin of each dimension (normally 1).
  307.      If more than one argument is given, dimsof returns the dimension
  308.      list of the result of binary operations between all the objects,
  309.      or nil if the objects are not conformable.
  310.   SEE ALSO: typeof, structof, numberof, sizeof, orgsof
  311.  */
  312.  
  313. extern orgsof;
  314. /* DOCUMENT orgsof(object)
  315.      returns a vector of integers describing the dimensions of OBJECT.
  316.      The format of the vector is [number of dims, origin1, origin2, ...].
  317.      By default, dimension origins are ignored, but use_origins changes
  318.      this.  The dimsof function returns the length of each dimension.
  319.      *** NOTE NOTE NOTE ***
  320.      Unless use_origins(1) is in effect, orgsof will always return
  321.      1 for all of the originI in the list.  Thus, whether use_origins(1)
  322.      is in effect or not, you are guaranteed that x(orgsof(x)(2)) is the
  323.      first element of x.
  324.   SEE ALSO: dimsof, typeof, structof, numberof, sizeof, use_origins
  325.  */
  326.  
  327. extern use_origins;
  328. /* DOCUMENT dummy= use_origins(dont_force)
  329.      Yorick array dimensions have an origin as well as a length.
  330.      By default, this origin is 1 (like FORTRAN arrays, unlike C
  331.      arrays).  However, the array function and the pseudo-index (-)
  332.      can be used to produce arrays with other origins.
  333.  
  334.      Initially, the origin of an array index is ignored by Yorick; the
  335.      first element of any array has index 1.  You can change this
  336.      default behavior by calling use_origins with non-zero DONT_FORCE,
  337.      and restore the default behavior by calling use_origins(0).
  338.  
  339.      When the returned object DUMMY is destroyed, either by return from
  340.      the function in which it is a local variable, or by explicit
  341.      redefintion of the last reference to it, the treatment of array
  342.      index origins reverts to the behavior prior to the call to
  343.      use_origins.  Thus, you can call use_origins at the top of a
  344.      function and not worry about restoring the external behavior
  345.      before every possible return (including errors).
  346.  
  347.   SEE ALSO: array, dimsof, orgsof
  348.  */
  349.  
  350. extern sizeof;
  351. /* DOCUMENT sizeof(object)
  352.      returns the size of the object in bytes, or 0 for non-array objects.
  353.      sizeof(structure_definition) returns the number of bytes per instance.
  354.      sizeof(binary_file) returns the file size in bytes.
  355.   SEE ALSO: dimsof, typeof, structof, numberof
  356.  */
  357.  
  358. extern numberof;
  359. /* DOCUMENT numberof(object)
  360.      returns the number of elements if object is an array, or 0 if not.
  361.   SEE ALSO: sizeof, dimsof, typeof, structof
  362.  */
  363.  
  364. extern typeof;
  365. /* DOCUMENT typeof(object)
  366.      returns a string describing the type of object.  For the basic
  367.      data types, these are "char", "short", "int", "long", "float",
  368.      "double", "complex", "string", "pointer", "struct_instance",
  369.      "void", "range", "struct_definition", "function", "builtin",
  370.      and "stream".
  371.   SEE ALSO: structof, dimsof, sizeof, numberof, nameof
  372.  */
  373.  
  374. extern nameof;
  375. /* DOCUMENT nameof(object)
  376.      If OBJECT is a function or a structure definition, returns the
  377.      name of the func or struct as it was defined (not necessarily
  378.      the name of the variable passed to the nameof function).
  379.   SEE ALSO: typeof
  380.  */
  381.  
  382. /*--------------------------------------------------------------------------*/
  383.  
  384. extern print;
  385. /* DOCUMENT print, object1, object2, object3, ...
  386.          or print(object1, object2, object3, ...)
  387.      prints an ASCII representation of the OBJECTs, in roughly the format
  388.      they could appear in Yorick source code.  When invoked as a subroutine
  389.      (in the first form), output is to the terminal.  When invoked as a
  390.      function (int the second form), the output is stored as a vector of
  391.      strings, one string per line that would have been output.
  392.      Printing a structure definition prints the structure definition;
  393.      printing a function prints its "func" definition; printing files,
  394.      bookmarks, and other objects generally provides some sort of
  395.      useful description of the object.
  396.   SEE ALSO: pr1, print_format, write, exit, error, nameof, typeof
  397.  */
  398.  
  399. func pr1(x)
  400. /* DOCUMENT pr1(x)
  401.      returns text representing expression X, equivalent to print(X)(1).
  402.    SEE ALSO: print, swrite
  403.  */
  404. { return print(x)(1); }
  405.  
  406. extern print_format;
  407. /* DOCUMENT print_format, line_length, char=, short=, int=, float=,
  408.                           double=, complex=, pointer=
  409.      sets the format string the print function will use for each of
  410.      the basic data types.  Yorick format strings are the same as the
  411.      format strings for the printf function defined in the ANSI C standard.
  412.      The default strings may be restored individually by setting the
  413.      associated format string to ""; all defaults are restored if
  414.      print_format is invoked with no arguments.  The default format strings
  415.      are:  "0x%02x", "%d", "%d", "%ld", "%g", "%g", and "%g%+gi".
  416.      Note that char and short values are converted to int before being
  417.      passed to printf, and that float is converted to double.
  418.      If present, an integer positional argument is taken as the line
  419.      length; <=0 restores the default line length of 80 characters.
  420.   SEE ALSO: print, write, nameof, typeof
  421.  */
  422.  
  423. /*--------------------------------------------------------------------------*/
  424.  
  425. extern is_array;
  426. /* DOCUMENT is_array(object)
  427.      returns 1 if OBJECT is an array data type (as opposed to a function,
  428.      structure definition, index range, I/O stream, etc.), else 0.
  429.      An array OBJECT can be written to or read from a binary file;
  430.      non-array Yorick data types cannot.
  431.   SEE ALSO: is_func, is_void, is_range, is_struct, is_stream
  432.  */
  433.  
  434. extern is_func;
  435. /* DOCUMENT is_func(object)
  436.      returns 1 if OBJECT is a Yorick interpreted function, 2 if OBJECT
  437.      is a built-in (that is, compiled) function, else 0.
  438.   SEE ALSO: is_array, is_void, is_range, is_struct, is_stream
  439.  */
  440.  
  441. extern is_void;
  442. /* DOCUMENT is_void(object)
  443.      returns 1 if OBJECT is nil (the one instance of the void data type),
  444.      else 0.
  445.   SEE ALSO: is_array, is_func, is_range, is_struct, is_stream
  446.  */
  447.  
  448. extern is_range;
  449. /* DOCUMENT is_range(object)
  450.      returns 1 if OBJECT is an index range (e.g.-  3:5 or 11:31:2),
  451.      else 0.
  452.   SEE ALSO: is_array, is_func, is_void, is_struct, is_stream
  453.  */
  454.  
  455. extern is_struct;
  456. /* DOCUMENT is_struct(object)
  457.      returns 1 if OBJECT is the definition of a Yorick struct, else 0.
  458.      Thus, is_struct(double) returns 1, but is_struct(1.0) returns 0.
  459.   SEE ALSO: is_array, is_func, is_void, is_range, is_stream
  460.  */
  461.  
  462. extern is_stream;
  463. /* DOCUMENT is_stream(object)
  464.      returns 1 if OBJECT is an I/O stream (usually a file), else 0.
  465.   SEE ALSO: is_array, is_func, is_void, is_range, is_struct
  466.  */
  467.  
  468. /*--------------------------------------------------------------------------*/
  469.  
  470. extern am_subroutine;
  471. /* DOCUMENT am_subroutine()
  472.      returns 1 if the current Yorick function was invoked as a subroutine,
  473.      else 0.  If am_subroutine() returns true, the result of the current
  474.      function will not be used, and need not be computed (the function
  475.      has been called for its side effects only).
  476.  */
  477.  
  478. /*--------------------------------------------------------------------------*/
  479.  
  480. extern sin;
  481. extern cos;
  482. extern tan;
  483. /* DOCUMENT sin(x)
  484.             cos(x)
  485.             tan(x)
  486.      returns the sine, cosine, or tangent of its argument,
  487.      which is in radians.
  488.   SEE ALSO: asin, acos, atan
  489.  */
  490.  
  491. extern asin;
  492. /* DOCUMENT asin(x)
  493.      returns the inverse sine of its argument, range [-pi/2, pi/2].
  494.   SEE ALSO: sin, cos, tan, asin, acos, atan
  495.  */
  496.  
  497. extern acos;
  498. /* DOCUMENT acos(x)
  499.      returns the inverse cosine of its argument, range [0, pi].
  500.   SEE ALSO: sin, cos, tan, asin, acos, atan
  501.  */
  502.  
  503. extern atan;
  504. /* DOCUMENT atan(x)
  505.          or atan(y, x)
  506.      returns the inverse tangent of its argument, range [-pi/2, pi/2].
  507.      In the two argument form, returns the angle from (1, 0) to (x, y),
  508.      in the range (-pi, pi], with atan(1, 0)==pi/2.  (If x>=0, this is
  509.      the same as atan(y/x).)
  510.   SEE ALSO: sin, cos, tan, asin, acos, atan
  511.  */
  512.  
  513. local pi;
  514. /* DOCUMENT pi
  515.      roughly 3.14159265358979323846264338327950288
  516.  */
  517. pi= 4.0*atan(1.0);    /* to double precision on this machine */
  518.  
  519. extern sinh;
  520. extern cosh;
  521. extern tanh;
  522. /* DOCUMENT sinh(x)
  523.             cosh(x)
  524.             tanh(x)
  525.      returns the hyperbolic sine, cosine, or tangent of its argument.
  526.   SEE ALSO: sech, csch, asinh, acosh, atanh
  527.  */
  528.  
  529. func sech(x) { y= tanh(x);  return sqrt(1.0-y*y); }
  530. func csch(x) { y= 1.0/tanh(x);  return sqrt(y*y-1.0); }
  531. /* DOCUMENT sech(x)
  532.             csch(x)
  533.      returns the hyperbolic secant (1/cosh) or cosecant (1/sinh) of
  534.      its argument, without overflowing for large x.
  535.   SEE ALSO: sinh, cosh, tanh, asinh, acosh, atanh
  536.  */
  537.  
  538. func asinh(x) { return log(x+sqrt(x*x+1.0)); }
  539. func acosh(x) { return log(x+sqrt(x*x-1.0)); }
  540. func atanh(x) { return 0.5*log((1.0+x)/(1.0-x)); }
  541. /* DOCUMENT asinh(x)
  542.             acosh(x)
  543.             atanh(x)
  544.      returns the inverse hyperbolic sine, cosine, or tangent of
  545.      its argument.  The range of acosh is >=0.0.
  546.   SEE ALSO: sinh, cosh, tanh, sech, csch
  547.  */
  548.  
  549. extern exp;
  550. /* DOCUMENT exp(x)
  551.      returns the exponential function of its argument (inverse of log).
  552.   SEE ALSO: log, log10, sinh, cosh, tanh, sech, csch
  553.  */
  554.  
  555. extern log;
  556. /* DOCUMENT log(x)
  557.      returns the natural logarithm of its argument (inverse of exp).
  558.   SEE ALSO: log10, exp, asinh, acosh, atanh
  559.  */
  560.  
  561. extern log10;
  562. /* DOCUMENT log10(x)
  563.      returns the base 10 logarithm of its argument (inverse of 10^x).
  564.   SEE ALSO: log, exp, asinh, acosh, atanh
  565.  */
  566.  
  567. extern sqrt;
  568. /* DOCUMENT sqrt(x)
  569.      returns the square root of its argument.
  570.   SEE ALSO: abs, also note the rms range function
  571.  */
  572.  
  573. extern poly;
  574. /* DOCUMENT poly(x, a0, a1, a2, ..., aN)
  575.      returns the polynomial  A0 + A1*x + A2*x^2 + ... + AN*X^N
  576.      The data type and dimensions of the result, and conformability rules
  577.      for the inputs are identical to those for the expression.
  578.  */
  579.  
  580. extern ceil;
  581. /* DOCUMENT ceil(x)
  582.      returns the smallest integer not less than x (no-op on integers).
  583.   SEE ALSO: floor
  584.  */
  585.  
  586. extern floor;
  587. /* DOCUMENT floor(x)
  588.      returns the largest integer not greater than x (no-op on integers).
  589.   SEE ALSO: ceil
  590.  */
  591.  
  592. extern abs;
  593. /* DOCUMENT abs(x)
  594.          or abs(x, y, z, ...)
  595.      returns the absolute value of its argument.
  596.      In the multi-argument form, returns sqrt(x^2+y^2+z^2+...).
  597.   SEE ALSO: sign, sqrt, also note the rms range function
  598.  */
  599.  
  600. extern sign;
  601. /* DOCUMENT sign(x)
  602.      returns algebraic sign of it argument, or closest point on the
  603.      unit circle for complex x.  Guaranteed that x==sign(x)*abs(x).
  604.      sign(0)==+1.
  605.   SEE ALSO: abs
  606.  */
  607.  
  608. extern conj;
  609. /* DOCUMENT conj(x)
  610.      returns the complex conjugate of its argument.
  611.  */
  612.  
  613. extern random;
  614. extern random_seed;
  615. /* DOCUMENT random(dimension_list)
  616.             random_seed, seed
  617.      returns an array of random double values with the given
  618.      DIMENSION_LIST (nil for a scalar result), uniformly distributed
  619.      on the interval from 0.0 to 1.0.
  620.      The algorithm is from Press and Teukolsky, Computers in Physics,
  621.      vol. 6, no. 5, Sep/Oct 1992 (ran2).  They offer a reward of $1000
  622.      to anyone who can exhibit a statistical test that this random
  623.      number generator fails in a "non-trivial" way.
  624.      The random_seed call reinitializes the random number sequence;
  625.      SEED should be between 0.0 and 1.0 non-inclusive; if SEED is
  626.      omitted, nil, or out of range, the sequence is reinitialized as
  627.      when Yorick starts.
  628.      The numbers are actually at the centers of 2147483562 equal width
  629.      bins on the interval [0,1].  Although only these 2 billion numbers
  630.      are possible, the period of the generator is roughly 2.3e18.
  631.  
  632.    SEE ALSO: randomize
  633.  */
  634.  
  635. func randomize(void)
  636. /* DOCUMENT randomize
  637.             randomize()
  638.      set the seed for random "randomly" (based on the timer clock
  639.      and the current state of random).  As a function, returns the
  640.      value of the seed passed to random_seed.
  641.  
  642.    SEE ALSO: random, random_seed
  643.  */
  644. {
  645.   seed= array(0., 3);
  646.   timer, seed;
  647.   seed= pi*sum(abs(seed));
  648.   while (seed > 0.9) seed*= 0.1;
  649.   seed+= 0.05;
  650.   random_seed, seed;
  651.   return seed;
  652. }
  653.  
  654. /*--------------------------------------------------------------------------*/
  655.  
  656. extern min;
  657. /* DOCUMENT min(x)
  658.          or min(x, y, z, ...)
  659.      returns the scalar minimum value of its array argument, or, if
  660.      more than one argument is supplied, returns an array of the
  661.      minimum value for each array element among the several arguments.
  662.      In the multi-argument case, the arguments must be conformable.
  663.   SEE ALSO: max, sum, avg
  664.  */
  665.  
  666. extern max;
  667. /* DOCUMENT max(x)
  668.          or max(x, y, z, ...)
  669.      returns the scalar maximum value of its array argument, or, if
  670.      more than one argument is supplied, returns an array of the
  671.      maximum value for each array element among the several arguments.
  672.      In the multi-argument case, the arguments must be conformable.
  673.   SEE ALSO: min, sum, avg
  674.  */
  675.  
  676. extern sum;
  677. /* DOCUMENT sum(x)
  678.      returns the scalar sum of all elements of its array argument.
  679.   SEE ALSO: avg, min, max
  680.  */
  681.  
  682. extern avg;
  683. /* DOCUMENT avg(x)
  684.      returns the scalar average of all elements of its array argument.
  685.   SEE ALSO: sum, min, max
  686.  */
  687.  
  688. extern allof;
  689. extern anyof;
  690. extern noneof;
  691. extern nallof;
  692. /* DOCUMENT allof(x)
  693.             anyof(x)
  694.             nallof(x)
  695.             noneof(x)
  696.      Respectively:
  697.       returns 1 if every element of the array x is non-zero, else 0.
  698.       returns 1 if at least one element of the array x is non-zero, else 0.
  699.       returns 1 if at least one element of the array x is zero, else 0.
  700.       returns 1 if every element of the array x is zero, else 0.
  701.   SEE ALSO: allof, anyof, noneof, nallof, where, where2
  702.  */
  703.  
  704. extern where;
  705. /* DOCUMENT where(x)
  706.      returns the vector of longs which is the index list of non-zero
  707.      values in the array x.  Thus, where([[0,1,3],[2,0,4]]) would
  708.      return [2,3,4,6].  If noneof(x), where(x) is a special range
  709.      function which will return a nil value if used to index an array;
  710.      hence, if noneof(x), then x(where(x)) is nil.
  711.      If x is a non-zero scalar, then where(x) returns a scalar value.
  712.      The rather recondite behavior for scalars and noneof(x) provides
  713.      maximum performance when the merge function to be used with the
  714.      where function.
  715.   SEE ALSO: where2, merge, merge2 allof, anyof, noneof, nallof, sort
  716.  */
  717.  
  718. func where2(x)
  719. /* DOCUMENT where2(x)
  720.      like where(x), but the returned list is decomposed into indices
  721.      according to the dimensions of x.  The returned list is always
  722.      2 dimensional, with the second dimension the same as the dimension
  723.      of where(x).  The first dimension has length corresponding to the
  724.      number of dimensions of x.  Thus, where2([[0,1,3],[2,0,4]]) would
  725.      return [[2,1],[3,1],[1,2],[3,2]].
  726.      If noneof(x), where2 returns [] (i.e.- nil).
  727.   SEE ALSO: where, merge, merge2, allof, anyof, noneof, nallof, sort
  728.  */
  729. {
  730.   w= where(x);
  731.   /* Since the result of where2 cannot be used as an index list, the
  732.      case noneof(x) can be disposed of more easily than with where.  */
  733.   if (!is_array(w)) return [];
  734.   d= dimsof(x);
  735.   n= d(1);
  736.   if (!n) return w;  /* catcall for passing a scalar */
  737.   d= d(2:);
  738.   o= orgsof(x)(2:);
  739.   w2= w(-:1:n,);
  740.   w-= o(1);
  741.   for (i=1 ; i<=n ; i++) {
  742.     w2(i,)= w%d(i) + o(i);
  743.     w/= d(i);
  744.   }
  745.   return w2;
  746. }
  747.  
  748. extern merge;
  749. /* DOCUMENT merge(true_expr, false_expr, condition)
  750.      returns the values TRUE_EXPR or FALSE_EXPR where CONDITION is
  751.      non-zero or zero, respectively.  The result has the data type of
  752.      TRUE_EXPR or FALSE_EXPR, promoted to the higher arithmetic type
  753.      if necessary.  The result has the dimensions of CONDITION.
  754.      The number of elements in TRUE_EXPR must match the number of
  755.      non-zero elements of CONDITION, and the number of elements in
  756.      FALSE_EXPR must match the number of zero elements of CONDITION.
  757.      (TRUE_EXPR or FALSE_EXPR should be nil if there are no such
  758.      elements of CONDITION.  Normally, TRUE_EXPR and FALSE_EXPR should
  759.      be 1-D arrays if they are not nil.)
  760.      This function is intended for vectorizing a function whose
  761.      domain is divided into two or more parts, as in:
  762.         func f(x) {
  763.       big= (x>=threshhold);
  764.       wb= where(big);
  765.       ws= where(!big);
  766.       if (is_array(wb)) {
  767.         xx= x(wb);
  768.         fb= <function of xx>
  769.       }
  770.       if (is_array(ws)) {
  771.         xx= x(ws);
  772.         fs= <function of xx>
  773.       }
  774.       return merge(fb, fs, big);
  775.     }
  776.    SEE ALSO: merge2, where
  777.  */
  778.  
  779. func merge2(t, f, c)
  780. /* DOCUMENT merge2(true_expr, false_expr, condition)
  781.      returns the values TRUE_EXPR or FALSE_EXPR where CONDITION is
  782.      non-zero or zero, respectively.  The result has the data type of
  783.      TRUE_EXPR or FALSE_EXPR, promoted to the higher arithmetic type
  784.      if necessary.  Unlike the merge function, TRUE_EXPR and FALSE_EXPR
  785.      must be conformable with each other, and with the CONDITION.
  786.    SEE ALSO: merge2, where
  787.  */
  788. {
  789.   dims= dimsof(t, f, c);
  790.   if (dims(1)) {
  791.     c+= array(structof(c), dims);
  792.     tt= array(structof(t), dims);  tt(..)= t;
  793.     ff= array(structof(f), dims);  ff(..)= f;
  794.   } else {
  795.     tt= t;
  796.     ff= f;
  797.   }
  798.   return merge(tt(where(c)), ff(where(!c)), c);
  799. }
  800.  
  801. /*--------------------------------------------------------------------------*/
  802.  
  803. extern grow;
  804. extern _;
  805. /* DOCUMENT grow, x, xnext1, xnext2, ...
  806.          or grow(x, xnext1, xnext2, ...)
  807.      or    _(x, xnext1, xnext2, ...)
  808.      lengthens the array X by appending XNEXT1, XNEXT2, etc. to its
  809.      final dimension.  If X is nil, X is first redefined to the first
  810.      non-nil XNEXT, and the remainder of the XNEXT list is processed
  811.      normally.  Each XNEXT is considered to have the same number of
  812.      dimensions as X, by appending unit-length dimensions if necessary.
  813.      All but this final dimension of each XNEXT must be right-conformable
  814.      (that is, conformable in the sense of the right hand side of an
  815.      assignment statement) with all but the final dimension of X.
  816.      The result has a final dimension which is the sum of the final
  817.      dimension of X and all the final dimensions of the XNEXT.  Nil
  818.      XNEXT are ignored.  The value of the result is obtained by
  819.      concatenating all the XNEXT to X, after any required broadcasts.
  820.  
  821.      If invoked as a function, grow returns the new value of X; in
  822.      this case, X may be an expression.  X must be a simple variable
  823.      reference for the subroutine form of grow; otherwise there is
  824.      nowhere to return the result.  The subroutine form is slightly
  825.      more efficient than the function form for the common usage:
  826.           x= grow(x, xnext1, xnext2)           is the same as
  827.       grow, x, xnext1, xnext2              the preferred form
  828.  
  829.      The _ function is a synonym for grow, for people who want this
  830.      operator to look like punctuation in their source code, on analogy
  831.      with the array building operator [a, b, c, ...].
  832.  
  833.      The _cat function is sometimes more appropriate than grow.
  834.  
  835.    SEE ALSO: _cat, array, compare with the array building operator [...]
  836.  */
  837.  
  838. extern indgen;
  839. /* DOCUMENT indgen(n)
  840.          or indgen(start:stop)
  841.          or indgen(start:stop:step)
  842.      returns "index generator" list -- an array of longs running from
  843.      1 to N, inclusive.  In the second and third forms, the index
  844.      values specified by the index range are returned.
  845.    SEE ALSO: span, spanl, array
  846.  */
  847.  
  848. extern span;
  849. /* DOCUMENT span(start, stop, n)
  850.          or span(start, stop, n, which)
  851.      returns array of N doubles equally spaced from START to STOP.
  852.      The START and STOP arguments may themselves be arrays, as long as
  853.      they are conformable.  In this case, the result will have one
  854.      dimension of length N in addition to dimsof(START, STOP).
  855.      By default, the result will be N-by-dimsof(START, STOP), but
  856.      if WHICH is specified, the new one of length N will be the
  857.      WHICHth.  WHICH may be non-positive to position the new
  858.      dimension relative to the end of dimsof(START, STOP); in
  859.      particular WHICH of 0 produces a result with dimensions
  860.      dimsof(START, STOP)-by-N.
  861.    SEE ALSO: spanl, indgen, array
  862.  */
  863.  
  864. func spanl(start, stop, n, which)
  865. /* DOCUMENT spanl(start, stop, n)
  866.          or spanl(start, stop, n, which)
  867.      similar to the span function, but the result array have N points
  868.      spaced at equal ratios from START to STOP (that is, equally
  869.      spaced logarithmically).  See span for discussion of WHICH argument.
  870.      START and STOP must have the same algebraic sign for this to make
  871.      any sense.
  872.    SEE ALSO: span, indgen, array
  873.  */
  874. {
  875.   return exp(span(log(abs(start)), log(abs(stop)), n,
  876.           (is_void(which)? 1 : which)))*sign(start);
  877. }
  878.  
  879. extern digitize;
  880. /* DOCUMENT digitize(x, bins)
  881.      returns an array of longs with dimsof(X), and values i such that
  882.      BINS(i-1) <= X < BINS(i) if BINS is monotonically increasing, or
  883.      BINS(i-1) > X >= BINS(i) if BINS is monotonically decreasing.
  884.      Beyond the bounds of BINS, returns either i=1 or i=numberof(BINS)+1
  885.      as appropriate.
  886.    SEE ALSO: histogram, interp, integ, sort, where, where2
  887.  */
  888.  
  889. extern histogram;
  890. /* DOCUMENT histogram(list)
  891.          or histogram(list, weight)
  892.      returns an array hist which counts the number of occurrences of each
  893.      element of the input index LIST, which must consist of positive
  894.      integers (1-origin index values into the result array):
  895.           histogram(list)(i) = number of occurrences of i in LIST
  896.  
  897.      A second argument WEIGHT must have the same shape as LIST; the result
  898.      will be the sum of WEIGHT:
  899.           histogram(list)(i) = sum of all WEIGHT(j) where LIST(j)==i
  900.  
  901.      The result of the single argument call will be of type long; the
  902.      result of the two argument call will be of type double (WEIGHT is
  903.      promoted to that type).  The input argument(s) may have any number
  904.      of dimensions; the result is always 1-D.
  905.  
  906.    KEYWORD: top=max_list_value
  907.      By default, the length of the result is max(LIST).  You may
  908.      specify that the result have a larger length by means of the TOP
  909.      keyword.  (Elements beyond max(LIST) will be 0, of course.)
  910.  
  911.    SEE ALSO: digitize, sort
  912.  */
  913.  
  914. extern interp;
  915. /* DOCUMENT interp(y, x, xp)
  916.          or interp(y, x, xp, which)
  917.      returns yp such that (XP, yp) lies on the piecewise linear curve
  918.      (X(i), Y(i)) (i=1, ..., numberof(X)).  Points beyond X(1) are set
  919.      to Y(1); points beyond X(0) are set to Y(0).  The array X must be
  920.      one dimensional, have numberof(X)>=2, and be either monotonically
  921.      increasing or monotonically decreasing.  The array Y may have more
  922.      than one dimension, but dimension WHICH must be the same length as
  923.      X.  WHICH defaults to 1, the first dimension of Y.  WHICH may be
  924.      non-positive to count dimensions from the end of Y; a WHICH of 0
  925.      means the final dimension of Y.  The result yp has dimsof(XP)
  926.      in place of the WHICH dimension of Y (if XP is scalar, the WHICH
  927.      dimension is not present).  (The dimensions of the result are the
  928.      same as if an index list with dimsof(XP) were placed in slot
  929.      WHICH of Y.)
  930.    SEE ALSO: integ, digitize, span
  931.  */
  932.  
  933. extern integ;
  934. /* DOCUMENT integ(y, x, xp)
  935.          or integ(y, x, xp, which)
  936.      See the interp function for an explanation of the meanings of the
  937.      arguments.  The integ function returns ypi which is the integral
  938.      of the piecewise linear curve (X(i), Y(i)) (i=1, ..., numberof(X))
  939.      from X(1) to XP.  The curve (X, Y) is regarded as constant outside
  940.      the bounds of X.  Note that X must be monotonically increasing or
  941.    SEE ALSO: interp, digitize, span
  942.  */
  943.  
  944. extern sort;
  945. /* DOCUMENT sort(x)
  946.          or sort(x, which)
  947.      returns an array of longs with dimsof(X) containing index values
  948.      such that X(sort(X)) is a monotonically increasing array.  X can
  949.      contain integer, real, or string values.  If X has more than one
  950.      dimension, WHICH determines the dimension to be sorted.  The
  951.      default WHICH is 1, corresponding to the first dimension of X.
  952.      WHICH can be non-positive to count dimensions from the end of X;
  953.      in particular a WHICH of 0 will sort the final dimension of X.
  954.  
  955.      WARNING: The sort function is non-deterministic if some of the
  956.               values of X are equal, because the Quick Sort algorithm
  957.           involves a random selection of a partition element.
  958.  
  959.      For information on sorting with multiple keys (and on making
  960.      sort deterministic), type the following:
  961.         #include "msort.i"
  962.         help, msort
  963.  
  964.    SEE ALSO: median, digitize, interp, integ, histogram
  965.  */
  966.  
  967. func median(x, which)
  968. /* DOCUMENT median(x)
  969.          or median(x, which)
  970.      returns the median of the array X.  The search for the median takes
  971.      place along the dimension of X specified by WHICH.  WHICH defaults
  972.      to 1, meaning the first index of X.  The median function returns an
  973.      array with one fewer dimension than its argument X (the WHICH
  974.      dimension of X is missing in the result), in exact analogy with
  975.      rank reducing index range functions.  If dimsof(X)(WHICH) is
  976.      odd, the result will have the same data type as X; if even, the
  977.      result will be a float or a double, since the median is defined
  978.      as the arithmetic mean between the two central values in that
  979.      case.
  980.    SEE ALSO: sort, built-in index range functions such as avg, rms
  981.  */
  982. {
  983.   if (is_void(which)) which= 1;
  984.   list= sort(x, which);
  985.   dims= dimsof(x);
  986.   if (which<1) which= dims(1)-which;
  987.   n= dims(1+which);
  988.   odd= n%2;
  989.   n/= 2;         /* index with half above, half below... */
  990.   n+= 1;         /* ...corrected for 1-origin */
  991.   stride= 1;
  992.   for (i=1 ; i<which ; i++) stride*= dims(1+i);
  993.   ldims= dims(1)-which+1;
  994.   /**/ local l;
  995.   reshape, l, &list, long, stride, grow(ldims, dims(1+which:));
  996.   lm= l(,n,..);
  997.   if (which<dims(1)) dims(1+which:-1)= dims(2+which:0);
  998.   --dims(1);
  999.   reshape, lm, long, dims;
  1000.   xm= x(lm);
  1001.   if (!odd) {     /* even length dimensions have more complicated median */
  1002.     reshape, lm;  /* undefine the LValue lm so following define works */
  1003.     lm= l(,n-1,..);
  1004.     reshape, lm, long, dims;
  1005.     xm= 0.5f*(xm+x(lm));
  1006.   }
  1007.   return xm;
  1008. }
  1009.  
  1010. extern transpose;
  1011. /* DOCUMENT transpose(x)
  1012.          or transpose(x, permutation1, permutation2, ...)
  1013.      transpose the first and last dimensions of array X.  In the second
  1014.      form, each PERMUTATION specifies a simple permutation of the
  1015.      dimensions of X.  These permutations are compounded left to right
  1016.      to determine the final permutation to be applied to the dimensions
  1017.      of X.  Each PERMUTATION is either an integer or a 1D array of
  1018.      integers.  A 1D array specifies a cyclic permutation of the
  1019.      dimensions as follows: [3, 5, 2] moves the 3rd dimension to the
  1020.      5th dimension, the 5th dimension to the 2nd dimension, and the 2nd
  1021.      dimension to the 3rd dimension.  Non-positive numbers count from the
  1022.      end of the dimension list of X, so that 0 is the final dimension,
  1023.      -1 in the next to last, etc.  A scalar PERMUTATION is a shorthand
  1024.      for a cyclic permutation of all of the dimensions of X.  The value
  1025.      of the scalar is the dimension to which the 1st dimension will move.
  1026.  
  1027.      Examples:  Let x have dimsof(x) equal [6, 1,2,3,4,5,6] in order
  1028.         to be able to easily identify a dimension by its length. Then:
  1029.     dimsof(x)                          == [6, 1,2,3,4,5,6]
  1030.     dimsof(transpose(x))               == [6, 6,2,3,4,5,1]
  1031.         dimsof(transpose(x,[1,2]))         == [6, 2,1,3,4,5,6]
  1032.     dimsof(transpose(x,[1,0]))         == [6, 6,2,3,4,5,1]
  1033.     dimsof(transpose(x,2))             == [6, 6,1,2,3,4,5]
  1034.     dimsof(transpose(x,0))             == [6, 2,3,4,5,6,1]
  1035.     dimsof(transpose(x,3))             == [6, 5,6,1,2,3,4]
  1036.     dimsof(transpose(x,[4,6,3],[2,5])) == [6, 1,5,6,3,2,4]
  1037.  */
  1038.  
  1039. /*--------------------------------------------------------------------------*/
  1040.  
  1041. extern strlen;
  1042. /* DOCUMENT strlen(string_array)
  1043.      returns an long array with dimsof(STRING_ARRAY) containing the
  1044.      lengths of the strings.  The null string (0) is considered to
  1045.      have length 0, just like "".
  1046.    SEE ALSO: strmatch, strpart, strtok
  1047.  */
  1048.  
  1049. extern strtok;
  1050. /* DOCUMENT strtok(string_array, delimiters)
  1051.          or strtok(string_array)
  1052.      strips the first token off of each string in STRING_ARRAY.
  1053.      A token is delimited by any of the characters in the string
  1054.      DELIMITERS.  If DELIMITERS is blank, nil, or not given, the
  1055.      default DELIMITERS is " \t\n" (blanks, tabs, or newlines).
  1056.      The result is a string array ts with dimensions
  1057.      2-by-dimsof(STRING_ARRAY); ts(1,) is the first token, and
  1058.      ts(2,) is the remainder of the string (the character which
  1059.      terminated the first token will be in neither of these parts).
  1060.      The ts(2,) part will be 0 (i.e.- the null string) if no more
  1061.      characters remain after ts(1,); the ts(1,) part will be 0 if
  1062.      no token was present.  A STRING_ARRAY element may be 0, in
  1063.      which case (0, 0) is returned for that element.
  1064.    SEE ALSO: strmatch, strpart, strlen
  1065.  */
  1066.  
  1067. extern strmatch;
  1068. /* DOCUMENT strmatch(string_array, pattern)
  1069.          or strmatch(string_array, pattern, case_fold)
  1070.      returns an int array with dimsof(STRING_ARRAY) with 0 where
  1071.      PATTERN was not found in STRING_ARRAY and 1 where it was found.
  1072.      If CASE_FOLD is specified and non-0, the pattern match is
  1073.      insensitive to case, that is, an upper case letter will match
  1074.      the same lower case letter and vice-versa.
  1075.    SEE ALSO: strtok, strpart, strlen
  1076.  */
  1077.  
  1078. extern strpart;
  1079. /* DOCUMENT strpart(string_array, m:n)
  1080.       returns another string array with the same dimensions as
  1081.       STRING_ARRAY which consists of characters M through N of
  1082.       the original strings.  M and N are 1-origin indices; if
  1083.       M is omitted, the default is 1; if N is omitted, the default
  1084.       is the end of the string.  If M or N is non-positive, it is
  1085.       interpreted as an index relative to the end of the string,
  1086.       with 0 being the last character, -1 next to last, etc.
  1087.       Finally, the returned string will be shorter than N-M+1
  1088.       characters if the original doesn't have an Mth or Nth
  1089.       character, with "" (note that this is otherwise impossible)
  1090.       if neither an Mth nor an Nth character exists.  A 0
  1091.       is returned for any string which was 0 on input.
  1092.    SEE ALSO: strmatch, strtok, strlen
  1093.  */
  1094.  
  1095. /*--------------------------------------------------------------------------*/
  1096.  
  1097. extern open;
  1098. /* DOCUMENT f= open(filename)
  1099.          or f= open(filename, filemode)
  1100.          or f= open(filename, filemode, errmode)
  1101.      opens the file FILENAME according to FILEMODE (both are strings).
  1102.      If ERRMODE is non-nil and non-zero, fail by returning nil F,
  1103.      otherwise failure to open or create the file is a runtime error.
  1104.  
  1105.      To use ERRMODE to check for the existence of a file:
  1106.         if (open(filename,,1)) file_exists;
  1107.     else file_does_not_exist;
  1108.  
  1109.      The return value F is an IOStream (or just stream for short).  When
  1110.      the last reference to this return value is discarded, the file will
  1111.      be closed.  The file can also be explicitly closed with the close
  1112.      function.  The FILEMODE determines whether the file is to be
  1113.      opened in read, write, or update mode, and whether writes are
  1114.      restricted to the end-of-file (append mode).  FILEMODE also
  1115.      determines whether the file is opened as a text file or as a
  1116.      binary file.  FILEMODE can have the following values, which are
  1117.      the same as for the ANSI standard fopen function:
  1118.         "r"     - read only
  1119.         "w"     - write only, random access, existing file overwritten
  1120.     "a"     - write only, forced to end-of-file,
  1121.             existing file preserved
  1122.     "r+"    - read/write, random access, existing file preserved
  1123.     "w+"    - read/write, random access, existing file overwritten
  1124.     "a+"    - read/write, reads random access,
  1125.             writes forced to end-of-file, existing file preserved
  1126.     "rb"  "wb"  "ab"  "r+b"  "rb+"  "w+b"  "wb+"  "a+b"  "ab+"
  1127.             without b means text file, with b means binary file
  1128.      The default FILEMODE is "r" -- open an existing text file for
  1129.      reading.
  1130.  
  1131.      The read and write functions perform I/O on text files.
  1132.      I/O to binary files may be performed explicitly using the save
  1133.      and restore functions, or implicitly by using the stream variable
  1134.      F as if it were a data structure instance (e.g.- f.x refers to
  1135.      variable x in the binary file f).
  1136.   SEE ALSO: create, close, read, write, rdline, bookmark, backup,
  1137.             rename, remove, save, restore
  1138.  */
  1139.  
  1140. func create(filename)
  1141. /* DOCUMENT f= create(filename)
  1142.      is a synonym for       f= open(filename, "w")
  1143.      Creates a new text file FILENAME, destroying any existing file of
  1144.      that name.  Use the write function to write into the file F.
  1145.    SEE ALSO: write, close, open
  1146.  */
  1147. { return open(filename, "w"); }
  1148.  
  1149. extern close;
  1150. /* DOCUMENT close, f
  1151.      closes the I/O stream F (returned earlier by the open function).
  1152.      If F is a simple variable reference (as opposed to an expression),
  1153.      the close function will set F to nil.  If F is the only reference
  1154.      to the I/O stream, then "close, f" is equivalent to "f= []".
  1155.      Otherwise, "close, f" will close the file (so that subsequent
  1156.      I/O operations will fail) and print a warning message about the
  1157.      outstanding ("stale") references.
  1158.   SEE ALSO: open, read, write, rdline, bookmark, backup, save, restore,
  1159.             rename, remove
  1160.  */
  1161.  
  1162. extern rename;
  1163. extern remove;
  1164. /* DOCUMENT rename, old_filename, new_filename
  1165.             remove filename
  1166.      rename or remove a file.
  1167.    SEE ALSO: open, close, openb, closeb
  1168.  */
  1169.  
  1170. extern read;
  1171. extern sread;
  1172. /* DOCUMENT n= read(f, format=fstring, obj1, obj2, ...)
  1173.          or n= read(prompt= pstring, format=fstring, obj1, obj2, ...)
  1174.      or n= sread(source, format=fstring, obj1, obj2, ...)
  1175.      reads text from I/O stream F (1st form), or from the keyboard (2nd
  1176.      form), or from the string or string array SOURCE (3rd form),
  1177.      interprets it according to the optional FSTRING, and uses that
  1178.      interpretation to assign values to OBJ1, OBJ2, ...  If the input
  1179.      is taken from the keyboard, the optional prompt PSTRING (default
  1180.      "read> ") is printed before each line is read.  The Yorick write
  1181.      function does not interact with the read function -- writes are
  1182.      always to end-of-file, and do not affect the sequence of lines
  1183.      returned by read.  The backup (and bookmark) function is the
  1184.      only way to change the sequence of lines returned by read.
  1185.  
  1186.      There must be one non-supressed conversion specifier (see below)
  1187.      in FSTRING for each OBJ to be read; the type of the conversion
  1188.      specifier must generally match the type of the OBJ.  That is,
  1189.      an integer OBJ requires an integer specifier (d, i, o, u, or x)
  1190.      in FSTRING, a real OBJ requires a real specifier (e, f, or g),
  1191.      and a string OBJ requires a string specifier (s or []).  An OBJ
  1192.      may not be complex, a pointer, a structure instance, or any non-
  1193.      array Yorick object.  If FSTRING is not supplied, or if it has
  1194.      fewer conversion specifiers than the number of OBJ arguments,
  1195.      then Yorick supplies default specifiers ("%ld" for integers,
  1196.      "%lg" for reals, and "%s" for strings).  If FSTRING contains more
  1197.      specifiers than there are OBJ arguments, the part of FSTRING
  1198.      beginning with the first specifier with no OBJ is ignored.
  1199.  
  1200.      The OBJ may be scalar or arrays, but the dimensions of every OBJ
  1201.      must be identical.  If the OBJ are arrays, Yorick behaves as
  1202.      if the read were called in a loop numberof(OBJ1) times, filling
  1203.      one array element of each of the OBJ according to FSTRING on
  1204.      each pass through the loop.  (Note that this behavior includes
  1205.      the case of reading columns of numbers by a single call to read.)
  1206.  
  1207.      The return value N is the total number of scalar assignments
  1208.      which were made as a result of this call.  (If there were 4
  1209.      OBJ arguments, and each was an array with 17 elements, a return
  1210.      value of N==35 would mean the following:  The first 8 elements
  1211.      of OBJ1, OBJ2, OBJ3, and OBJ4 were read, and the 9th element of
  1212.      OBJ1, OBJ2, and OBJ3 was read.)  The read function sets any
  1213.      elements of the OBJ which were not read to zero -- hence,
  1214.      independent of the returned N, the all of the old data in the
  1215.      OBJ arguments is overwritten.
  1216.  
  1217.      The read or sread functions continue reading until either:
  1218.      (1) all elements of all OBJ have been filled, or (2) end-of-file
  1219.      (or end of SOURCE for sread) is reached ("input failure"), or
  1220.      (3) part of FSTRING or a conversion specifier supplied by
  1221.      default fails to match the source text ("matching failure").
  1222.  
  1223.      The FSTRING is composed of a series of "directives" which are
  1224.      (1) whitespace -- means to skip any amount of whitespace in the
  1225.          source text
  1226.      (2) characters other than whitespace and % -- must match the
  1227.          characters in the source text exactly, or matching failure
  1228.      occurs and the read operation stops
  1229.      (3) conversion specifiers beginning with % and ending with a
  1230.          character specifying the type of conversion -- optionally
  1231.      skip whitespace, then convert as many characters as
  1232.      continue to "look like" the conversion type, possibly
  1233.      producing a matching failure
  1234.      The conversion specifier is of the form %*WSC, where:
  1235.      * is either the character '*' or not present
  1236.        A specifier beginning with %* does not correspond to any of
  1237.        the OBJ; the converted value will be discarded.
  1238.      W is either a positive decimal integer specifying the maximum
  1239.        field width (not including any skipped leading whitespace),
  1240.        or not present if any number of characters up to end-of-line
  1241.        is acceptable.
  1242.      S is either one of the characters 'h', 'l', or 'L', or not
  1243.        present.  Yorick allows this for compatibility with the C
  1244.        library functions, but ignores it.
  1245.      C is a character specifying the type of conversion:
  1246.        d   - decimal integer
  1247.        i   - decimal, octal (leading 0), or hex (leading 0x) integer
  1248.        o   - octal integer
  1249.        u   - unsigned decimal integer (same as d for Yorick)
  1250.        x, X            - hex integer
  1251.        e, f, g, E, G   - floating point real
  1252.        s   - string of non-whitespace characters
  1253.        [xxx]   - (xxx is any sequence of characters) longest string
  1254.                  of characters matching those in the list
  1255.        [^xxx]  - longest string of characters NOT matching those in
  1256.                  the list (this is how you can extend %s to be
  1257.          delimited by something other than whitespace)
  1258.        %   - the ordinary % character; complete conversion
  1259.              specification must be "%%"
  1260.  
  1261.      The read function is modeled on the ANSI standard C library
  1262.      fscanf and sscanf functions, but differs in several respects:
  1263.        (1) Yorick's read cannot handle the %c, %p, or %n conversion
  1264.            specifiers in FSTRING.
  1265.        (2) Yorick's read never results in a portion of a line
  1266.            being read -- any unused part of a line is simply discarded
  1267.        (end FSTRING with "%[^\n]" if you want to save the trailing
  1268.        part of an input line).
  1269.        (3) As a side effect of (2), there are some differences between
  1270.            fscanf and Yorick's read in how whitespace extending across
  1271.        newlines is handled.
  1272.    SEE ALSO: rdline, write, open, close, bookmark, backup, save, restore,
  1273.              read_n
  1274.  */
  1275.  
  1276. extern rdline;
  1277. /* DOCUMENT rdline(f)
  1278.          or rdline(f, n, prompt= pstring)
  1279.      returns next line from stream F (stdin if F nil).  If N is non-nil,
  1280.      returns a string array containing the next N lines of F.  If
  1281.      end-of-file occurs, rdline returns nil strings.  If F is nil,
  1282.      uses the PSTRING to prompt for input (default "read> ").
  1283.    SEE ALSO: read, open, close, bookmark, backup, read_n
  1284.  */
  1285.  
  1286. func read_n(f, &n0, &n1, &n2, &n3, &n4, &n5, &n6, &n7, &n8, &n9)
  1287. /* DOCUMENT read_n, f, n0, n1, n2, ...
  1288.      grabs the next numbers N0, N1, N2, ... from file F, skipping over
  1289.      any whitespace, comma, semicolon, or colon delimited tokens which
  1290.      are not numbers.  (Actually, only the first and last characters of
  1291.      the token have to look like a number -- 4xxx3 would be read as 4.)
  1292.      ***WARNING*** at most ten Ns are allowed
  1293.      The Ns can be arrays, provided all have the same dimensions.
  1294.    SEE ALSO: read, rdline
  1295.  */
  1296. {
  1297.   require, "readn.i";
  1298.   return raw_read_n(f, n0, n1, n2, n3, n4, n5, n6, n7, n8, n9);
  1299. }
  1300.  
  1301. extern write;
  1302. extern swrite;
  1303. /* DOCUMENT n= write(f, format=fstring, linesize=l, obj1, obj2, ...)
  1304.             n= write(format=fstring, linesize=l, obj1, obj2, ...)
  1305.      or strings= swrite(format=fstring, linesize=l, obj1, obj2, ...)
  1306.      writes text to I/O stream F (1st form), or to the terminal (2nd
  1307.      form), or to the STRINGS string array (3rd form), representing
  1308.      arrays OBJ1, OBJ2, ..., according to the optional FSTRING.  The
  1309.      optional linesize L defaults to 80 characters, and helps restrict
  1310.      line lengths when FSTRING is not given, or does not contain
  1311.      newline directives.  The write function always appends to the
  1312.      end of a text file; the position for a sequence of reads is
  1313.      not affected by intervening writes.
  1314.  
  1315.      There must be one conversion specifier (see below) in FSTRING for
  1316.      each OBJ to be written; the type of the conversion specifier must
  1317.      generally match the type of the OBJ.  That is, an integer OBJ
  1318.      requires an integer specifier (d, i, o, u, x, or c) in FSTRING,
  1319.      a real OBJ requires a real specifier (e, f, or g), a string OBJ
  1320.      requires the string specifier (s), and a pointer OBJ requires a
  1321.      the pointer specifier (p).  An OBJ may not be complex, a structure
  1322.      instance, or any non-array Yorick object.  If FSTRING is not
  1323.      supplied, or if it has fewer conversion specifiers than the
  1324.      number of OBJ arguments, then Yorick supplies default specifiers
  1325.      (" %8ld" for integers, " %14.6lg" for reals, " %s" for strings, and
  1326.      " %8p" for pointers).  If FSTRING contains more specifiers than
  1327.      there are OBJ arguments, the part of FSTRING beginning with the
  1328.      first specifier with no OBJ is ignored.
  1329.  
  1330.      The OBJ may be scalar or arrays, but the dimensions of the OBJ
  1331.      must be conformable.  If the OBJ are arrays, Yorick behaves as
  1332.      if he write were called in a loop dimsof(OBJ1, OBJ2, ...) times,
  1333.      writing one array element of each of the OBJ according to FSTRING
  1334.      on each pass through the loop.  The swrite function returns a
  1335.      string array with dimensions dimsof(OBJ1, OBJ2, ...).  The write
  1336.      function inserts a newline between passes through the array if
  1337.      the line produced by the previous pass did not end with a
  1338.      newline, and if the total number of characters output since the
  1339.      previous inserted newline, plus the number of characters about
  1340.      to be written on the current pass, would exceed L characters
  1341.      (L defaults to 80).  The write function returns the total
  1342.      number of characters output.
  1343.  
  1344.      The FSTRING is composed of a series of "directives" which are
  1345.      (1) characters other than % -- copied directly to output
  1346.      (2) conversion specifiers beginning with % and ending with a
  1347.          character specifying the type of conversion -- specify
  1348.      how to convert an OBJ into characters for output
  1349.      The conversion specifier is of the form %FW.PSC, where:
  1350.      F is zero or more optional flags:
  1351.        - left justify in field width
  1352.        + signed conversion will begin with either + or -
  1353.          (space) signed conversion  will begin with either space or -
  1354.        # alternate form (see description of each type below)
  1355.        0 pad field width with leading 0s instead of leading spaces
  1356.      W is either a decimal integer specifying the minimum field width
  1357.        (padded as specified by flags), or not present to use the
  1358.        minimum number of characters required.
  1359.      .P is either a decimal integer specifying the precision of the
  1360.        result, or not present to get the default.  For integers, this
  1361.        is the number of digits to be printed (possibly forcing leading
  1362.        zeroes), and defaults to 1.  For reals, this is the number of
  1363.        digits after the decimal point, and defaults to 6.  For strings,
  1364.        this is the maximum number of characters to print, and defaults
  1365.        to infinity.
  1366.      S is either one of the characters 'h', 'l', or 'L', or not
  1367.        present.  Yorick allows this for compatibility with the C
  1368.        library functions, but ignores it.
  1369.      C is a character specifying the type of conversion:
  1370.        d, i  - decimal integer
  1371.        o     - octal integer (# forces leading 0)
  1372.        u     - unsigned decimal integer (same as d for Yorick)
  1373.        x, X            - hex integer (# forces leading 0x)
  1374.        f     - floating point real in fixed point notation
  1375.                (# forces decimal)
  1376.        e, E  - floating point real in scientific notation
  1377.        g, G  - floating point real in fixed or scientific notation
  1378.                depending on the value converted (# forces decimal)
  1379.        s   - string of ASCII characters
  1380.        c   - integer printed as corresponding ASCII character
  1381.        p   - pointer
  1382.        %   - the ordinary % character; complete conversion
  1383.              specification must be "%%"
  1384.  
  1385.      The write function is modeled on the ANSI standard C library
  1386.      fprintf and sprintf functions, but differs in several respects:
  1387.        (1) Yorick's write cannot handle the %n conversion specifier
  1388.            in FSTRING.
  1389.        (2) Yorick's write may insert additional newlines if the OBJ
  1390.            are arrays, to avoid extremely long output lines.
  1391.    SEE ALSO: print, exit, error, read, rdline, open, close, save, restore
  1392.  */
  1393.  
  1394. extern bookmark;
  1395. extern backup;
  1396. /* DOCUMENT backup, f
  1397.          or bmark= bookmark(f)
  1398.             ...
  1399.             backup, f, bmark
  1400.      back up the text stream F, so that the next call to the read
  1401.      function returns the same line as the previous call to read
  1402.      (note that you can only back up one line).  If the optional
  1403.      second argument BMARK is supplied, restores the state of the
  1404.      file F to its state at the time the bookmark function was
  1405.      called.
  1406.      After a matching failure in read, use the single argument form
  1407.      of backup to reread the line containing the matching failure.
  1408.    SEE ALSO: read, rdline, open, close
  1409.  */
  1410.  
  1411. extern include;
  1412. extern require;
  1413. /* DOCUMENT #include "yorick_source.i"
  1414.             require, filename
  1415.             include, filename
  1416.          or include, filename, now
  1417.  
  1418.      #include is a parser directive, not a Yorick statement.  Use it
  1419.      to read Yorick source code which you have saved in a file; the
  1420.      file yorick_source.i will be read one line at a time, exactly as
  1421.      if you had typed those lines at the keyboard.  The following
  1422.      directories are searched (in this order) to find yorick_source.i:
  1423.  
  1424.         .               (current working directory)
  1425.     ~/Yorick        (your personal directory of Yorick functions)
  1426.     Y_SITE/include  (Yorick distribution library)
  1427.     Y_SITE/contrib  (contributed source at your site)
  1428.  
  1429.      To find out what is available in the Yorick/include directory,
  1430.      type:
  1431.          library
  1432.      You can also type
  1433.          Y_SITE
  1434.      to find the name of the site directory at your site, go to the
  1435.      include or contrib subdirectory, and browse through the *.i files.
  1436.      This is a good way to learn how to write a Yorick program.  Be
  1437.      alert for files like README as well.
  1438.  
  1439.      The require function checks to see whether FILENAME has already
  1440.      been included (actually whether any file with the same final
  1441.      path component has been included).  If so, require is a no-op,
  1442.      otherwise, the action is the same as the include function with
  1443.      NOW == 1.
  1444.  
  1445.      The include function causes Yorick to parse and execute FILENAME
  1446.      immediately.  The effect is similar to the #include parser
  1447.      directive, except the finding, parsing, and execution of FILENAME
  1448.      occurs at runtime.  If the NOW argument is given and positive,
  1449.      the include occurs immediately, if nil or 0, it occurs just before
  1450.      the next line would have been parsed.  If NOW is negative, the
  1451.      include file is pushed onto a stack, and will be popped off and
  1452.      parsed when all pending input has been processed.
  1453.  
  1454.      Unless you are writing a startup file, or have some truly bizarre
  1455.      technical reason for using the include function, use #include
  1456.      instead.  The functional form of include may involve recursive
  1457.      parsing, which you will not be able to understand without deep
  1458.      study.  Stick with #include.
  1459.  
  1460.    SEE ALSO: set_path, Y_SITE
  1461.  */
  1462.  
  1463. func library(void)
  1464. /* DOCUMENT library
  1465.      print the Y_SITE/include/README file at the terminal.
  1466.  */
  1467. {
  1468.   f= open(Y_SITE+"include/README");
  1469.   while ((line= rdline(f))) write, line;
  1470. }
  1471.  
  1472. /*--------------------------------------------------------------------------*/
  1473.  
  1474. extern cd;
  1475. /* DOCUMENT cd, directory_name
  1476.          or cd(directory_name)
  1477.      change current working directory to DIRECTORY_NAME, returning
  1478.      the expanded path name (i.e.- with leading environment variables,
  1479.      ., .., or ~ replaced by the actual pathname).  If called as a
  1480.      function, returns nil to indicate failure, otherwise failure
  1481.      causes a Yorick error.
  1482.    SEE ALSO: get_cwd, get_home, get_env, get_argv
  1483.  */
  1484.  
  1485. extern get_cwd;
  1486. extern get_home;
  1487. /* DOCUMENT get_cwd()
  1488.          or get_home()
  1489.      returns the pathname of the current working directory or of your
  1490.      home directory.
  1491.    SEE ALSO: cd, get_env, get_argv
  1492.  */
  1493.  
  1494. extern get_env;
  1495. /* DOCUMENT get_env(environment_variable_name)
  1496.      returns the environment variable (a string) associated with
  1497.      ENVIRONMENT_VARIABLE_NAME (calls ANSI getenv routine).
  1498.    SEE ALSO: cd, get_cwd, get_home, get_env, get_argv
  1499.  */
  1500.  
  1501. extern get_argv;
  1502. /* DOCUMENT get_argv()
  1503.      returns string array containing the argv from the command line.
  1504.      The -batch and batch_include.i arguments are removed (not returned).
  1505.    SEE ALSO: process_argv, cd, get_cwd, get_home, get_env, batch
  1506.  */
  1507.  
  1508. func process_argv(msg)
  1509. /* DOCUMENT remaining= process_argv()
  1510.        -or- remaining= process_argv("your startup message")
  1511.      Performs standard command line processing.  This function is
  1512.      invoked by the default custom.i file (in $Y_HOME/include); you
  1513.      can also invoke it from your personal ~/Yorick/custom.i file.
  1514.      The process_argv calls get_argv, removes any arguments of
  1515.      the form "-ifilename" or "-i filename" (the latter is a pair of
  1516.      arguments.  It returns any arguments not of this form as its
  1517.      result, after including any filenames it found in the order
  1518.      they appeared on the command line.
  1519.      The optional string argument may be an array of strings to print
  1520.      a multi-line message.
  1521.  
  1522.      A Yorick package may define the function get_command_line in
  1523.      order to feed process_argv something other than get_argv.
  1524.  
  1525.    SEE ALSO: batch
  1526.  */
  1527. {
  1528.   if (is_void(get_command_line)) command_line= get_argv();
  1529.   else command_line= get_command_line();
  1530.   if (numberof(command_line)>=2) {
  1531.     command_line= command_line(2:);
  1532.     mask= strmatch(strpart(command_line, 1:2), "-i");
  1533.     list= where(mask);
  1534.     n= numberof(list);
  1535.     for (i=1 ; i<=n ; i++) {
  1536.       file= strpart(command_line(list(i)), 3:);
  1537.       if (file=="") {
  1538.     if (list(i)==numberof(command_line)) break;  /* ignore trailing -i */
  1539.     file= command_line(list(i)+1);
  1540.     mask(list(i)+1)= 1;
  1541.       }
  1542.       include, file;
  1543.     }
  1544.     command_line= command_line(where(!mask));
  1545.   } else {
  1546.     command_line= [];
  1547.   }
  1548.   if (numberof(command_line)<1 || noneof(command_line=="-q")) {
  1549.     if (is_void(msg))
  1550.       msg= [
  1551. " Copyright (c) 1995.  The Regents of the University of California.",
  1552. " All rights reserved.  Yorick 1.2 ready.  For help type 'help'"];
  1553.     write, msg, format="%s\n";
  1554.   } else {
  1555.     command_line= command_line(where(command_line!="-q"));
  1556.   }
  1557.   return command_line;
  1558. }
  1559.  
  1560. /*--------------------------------------------------------------------------*/
  1561.  
  1562. func openb(filename, clogfile, update, open102=)
  1563. /* DOCUMENT file= openb(filename)
  1564.          or file= openb(filename, clogfile)
  1565.      open the existing file FILENAME for read-only binary I/O.
  1566.      (Use updateb or createb, respectively, to open an existing file
  1567.       with read-write access or to create a new file.)
  1568.      If the CLOGFILE argument is supplied, it represents the structure
  1569.      of FILENAME in the Clog binary data description language.
  1570.      After an openb, the file variable may be used to extract variables
  1571.      from the file as if it were a structure instance.  That is, the
  1572.      expression "file.var" refers to the variable "var" in file "file".
  1573.      A complete list of the variable names present in the file may
  1574.      be obtained using the get_vars function.  If the file contains
  1575.      history records, the jt and jc functions may be used to set the
  1576.      current record -- initially, the first record is current.
  1577.      The restore function may be used to make memory copies of data
  1578.      in the file; this will be faster than a large number of
  1579.      references to "file.var".
  1580.    SEE ALSO: updateb, createb, open, cd
  1581.              show, jt, jc, restore
  1582.              get_vars, get_times, get_ncycs, get_member, has_records
  1583.              set_blocksize, dump_clog, read_clog, recover_file
  1584.          openb_hooks, open102, close102, get_addrs
  1585.  */
  1586. {
  1587.   f= open(filename, (update? "r+b" : "rb"));
  1588.   if (!is_void(clogfile)) return read_clog(f, clogfile);
  1589.   if (!is_void(open102)) yPDBopen= ((open102&3)|(at_pdb_open&~3));
  1590.   else yPDBopen= at_pdb_open;
  1591.   for (hooks=openb_hooks ; hooks ; hooks=_cdr(hooks)) {
  1592.     if (_car(hooks)(f)) continue;
  1593.     if (has_records(f)) edit_times, f;  /* force increasing times */
  1594.     return f;
  1595.   }
  1596.   return [];
  1597. }
  1598.  
  1599. func show(f, pat)
  1600. /* DOCUMENT show, f
  1601.          or show, f, pat
  1602.          or show, f, 1
  1603.      prints a summary of the variables contained in binary file F.
  1604.      If there are too many variables, use the second form to select
  1605.      only those variables whose first few characters match PAT.
  1606.      In the third form, continues the previous show command where it
  1607.      left off -- this may be necessary for files with large numbers of
  1608.      variables.
  1609.      The variables are printed in alphabetical order down the columns.
  1610.      The print function can be used to obtain other information about F.
  1611.    SEE ALSO: openb, jt, jc
  1612.  */
  1613. {
  1614.   require, "show.i";
  1615.   raw_show, f, pat;
  1616. }
  1617.  
  1618. func collect(f, name)
  1619. /* DOCUMENT result= collect(f, name_string)
  1620.      scans through all records of the history file F accumulating the
  1621.      variable NAME_STRING into a single array with one additional
  1622.      index varying from 1 to the number of records.
  1623.  
  1624.      NAME_STRING can be either a simple variable name, or a name
  1625.      followed by up to four simple indices which are either nil, an
  1626.      integer, or an index range with constant limits.  (Note that
  1627.      0 or negative indices count from the end of a dimension.)
  1628.  
  1629.      Examples:
  1630.         collect(f, "xle")        -- collects the variable f.xle
  1631.     collect(f, "tr(2,2:)")   -- collects f.tr(2,2:)
  1632.     collect(f, "akap(2,-1:0,)") -- collects f.akap(2,-1:0,)
  1633.                  (i.e.- akap in the last two values of its
  1634.                     second index)
  1635.  
  1636.    SEE ALSO: get_times
  1637.  */
  1638. {
  1639.   require, "collec.i";
  1640.   return raw_collect(f, name);
  1641. }
  1642.  
  1643. extern get_member;
  1644. /* DOCUMENT get_member(f_or_s, member_name)
  1645.      returns F_OR_S member MEMBER_NAME, like F_OR_S.MEMBER_NAME syntax,
  1646.      but MEMBER_NAME can be a computed string.  The F_OR_S may be a
  1647.      binary file or a structure instance.
  1648.    SEE ALSO: openb
  1649.  */
  1650.  
  1651. extern read_clog;
  1652. /* DOCUMENT file= read_clog(file, clog_name)
  1653.      raw routine to set the binary data structure of FILE according
  1654.      to the text description in the Contents Log file CLOG_NAME.
  1655.  */
  1656.  
  1657. func recover_file(filename, clogfile)
  1658. /* DOCUMENT recover_file, filename
  1659.          or recover_file, filename, clogfile
  1660.      writes the descriptive information at the end of a corrupted
  1661.      binary file FILENAME from its Contents Log file CLOGFILE, which
  1662.      is FILENAME+"L" by default.
  1663.  */
  1664. {
  1665.   if (is_void(clogfile)) clogfile= filename+"L";
  1666.   if (clogfile==filename+"L") {  /* open clobbers this one */
  1667.     changed= 1;
  1668.     rename, clogfile, filename+"M";
  1669.     clogfile= filename+"M";
  1670.   } else {
  1671.     changed= 0;
  1672.   }
  1673.   f= open(filename, "r+b");
  1674.   i= array(char, 12);
  1675.   _read, f, 0, i;
  1676.   read_clog, f, clogfile;
  1677.   if (string(&i)=="!<<PDB:II>>!") _set_pdb, f, at_pdb_close;
  1678.   else _init_clog, f;
  1679.   close, f;
  1680.   if (changed) remove, clogfile;
  1681. }
  1682.  
  1683. extern _not_pdb;
  1684. /* DOCUMENT _not_pdb(file, familyOK)
  1685.      returns 1 if FILE is not a PDB file, otherwise returns 0 after
  1686.      setting the structure and data tables, and cataloguing any
  1687.      history records.  Used to open an existing file.  Also detects
  1688.      a file with an appended Clog description.
  1689.      Before calling _not_pdb, set the variable yPDBopen to the value
  1690.      of at_pdb_open you want to be in force.  (For historical reasons
  1691.      -- in order to allow for the open102 keyword to openb -- _not_pdb
  1692.      looks at the value of the variable yPDBopen, rather than at_pdb_open
  1693.      directly.)
  1694.  */
  1695.  
  1696. local close102, open102, close102_default;
  1697. /* DOCUMENT close102  is a keyword for createb or updateb,
  1698.             open102   is a keyword for openb or updateb
  1699.         close102_default   is a global variable (initially 0)
  1700.           ***Do not use close102_default -- use at_pdb_close
  1701.              -- this is for backward compatibility only***
  1702.  
  1703.         close102=1  means to close the PDB file "Major-Order:102"
  1704.         close102=0  means close it "Major-Order:101"
  1705.            if not specified, uses 1 if close102_default non-zero,
  1706.            otherwise the value specified in at_pdb_close
  1707.  
  1708.         open102=1   means to ignore what the PDB file says internally,
  1709.                     and open it as if it were "Major-Order:102"
  1710.         open102=0   (the default) means to assume the PDB file is
  1711.                         correctly writen
  1712.         open102=2   means to assume that the file is incorrectly
  1713.                     written, whichever way it is marked
  1714.         open102=3   means to ignore what the PDB file says internally,
  1715.                     and open it as if it were "Major-Order:101"
  1716.  
  1717.      The PDB file format comes in two styles, "Major-Order:101", and
  1718.      "Major-Order:102".  Yorick interprets these correctly by default,
  1719.      but other codes may ignore them, or write them incorrectly.
  1720.  
  1721.      Unlike Yorick, not all codes are able to correctly read both
  1722.      styles.  If you are writing a file which needs to be read by
  1723.      a "102 style" code, create it with the close102=1 keyword.
  1724.  
  1725.      If you notice that a file you though was a history file isn't, or
  1726.      that the dimensions of multi-dimensional variables are transposed
  1727.      from the order you expected, the code which wrote the file probably
  1728.      blew it.  Try openb("filename", open102=2).  The choices 1 and 3
  1729.      are for cases in which you know the writing code was supposed to
  1730.      write the file one way or the other, and you don't want to be
  1731.      bothered.
  1732.  
  1733.      The open102 and close102 keywords, if present, override the
  1734.      defaults in the variables at_pdb_open and at_pdb_close.
  1735.  
  1736.    SEE ALSO: at_pdb_open, at_pdb_close
  1737.  */
  1738. close102_default= [];
  1739.  
  1740. local at_pdb_open, at_pdb_close;
  1741. /* DOCUMENT at_pdb_open
  1742.             at_pdb_close
  1743.      bits for optional behavior when a PDB file is opened or closed:
  1744.  
  1745.      at_pdb_open:
  1746.      000  Major-Order:  value specified in file is correct
  1747.      001  Major-Order:102 always 
  1748.      002  Major-Order:  opposite from what file says
  1749.      003  Major-Order:101 always
  1750.  
  1751.      004  Strip Basis @... suffices from variable names (when possible)
  1752.           Danger!  If you do this and open a file for update, the variable
  1753.       names will be stripped when you close the file!
  1754.      010  Use Basis @history convention on input
  1755.  
  1756.      The 001 and 002 bits may be overridden by the open102 keyword.
  1757.      The default value of at_pdb_open is 010.
  1758.  
  1759.      at_pdb_close (the value at the time the file is opened or created
  1760.                    is remembered):
  1761.      001  Write Major-Order 102 PDB file
  1762.      002  Write PDB style history data
  1763.         The following are no-ops unless bit 002 is set:
  1764.      004  Use Basis @history convention on output
  1765.      010  Do NOT pack all history record variables into
  1766.           a single structure instance.
  1767.  
  1768.      The 001 bit may be overridden by the close102 keyword or if
  1769.      close102_default is non-zero.
  1770.      The default value of at_pdb_close is 007.
  1771.  
  1772.    SEE ALSO: close102_default
  1773.  */
  1774. at_pdb_open= 010;
  1775. at_pdb_close= 007;
  1776.  
  1777. func _not_pdbf(f) { return _not_pdb(f, 1); }
  1778.  
  1779. extern _init_pdb;
  1780. extern _set_pdb;
  1781. /* DOCUMENT _init_pdb, file, at_pdb_close
  1782.             _set_pdb, file, at_pdb_close
  1783.      initializes a PDB binary file.  Used after creating a new file --
  1784.      must be called AFTER the primitive data formats have been set.
  1785.      The _set_pdb call only sets the CloseHook, on the assumption that
  1786.      the file header has already been written (as in recover_file).
  1787.    SEE ALSO: createb, recover_file, at_pdb_close
  1788.  */
  1789.  
  1790. extern _init_clog;
  1791. /* DOCUMENT _init_clog, file
  1792.      initializes a Clog binary file.  Used after creating a new file --
  1793.      must be called AFTER the primitive data formats have been set.
  1794.  */
  1795.  
  1796. extern dump_clog;
  1797. /* DOCUMENT dump_clog, file, clog_name
  1798.      dumps a Contents Log of the binary file FILE into the text file
  1799.      CLOG_NAME.  Any previous file named CLOG_NAME is overwritten.
  1800.   SEE ALSO: openb
  1801.  */
  1802.  
  1803. func _not_cdf(file)
  1804. /* DOCUMENT _not_cdf(file)
  1805.      is like _not_pdb, but for netCDF files.
  1806.  */
  1807. {
  1808.   i= array(char, 4);
  1809.   _read, f, 0, i;
  1810.   if (string(&i)!="CDF\001") return 1;  /* test magic number */
  1811.   require, "netcdf.i";
  1812.   return raw_not_cdf(file);
  1813. }
  1814.  
  1815. local openb_hooks;
  1816. /* DOCUMENT openb_hooks
  1817.      list of functions to be tried by openb if the file to be
  1818.      opened is not a PDB file.  By default,
  1819.        openb_hooks= _lst(_not_pdbf, _not_cdf).
  1820.      The hook functions will be called with the file as argument
  1821.      (e.g.- _not_cdf(file)), beginning with _car(openb_hooks), until
  1822.      one of them returns 0.  Note that a hook should return 0 if it
  1823.      "recognizes" the file as one that it should be able to open, but
  1824.      finds that the file is misformatted (alternatively, it could call
  1825.      error to abort the whole process).
  1826.  */
  1827. openb_hooks= _lst(_not_pdbf, _not_cdf);
  1828.  
  1829. func createb(filename, primitives, close102=)
  1830. /* DOCUMENT file= createb(filename)
  1831.          or file= createb(filename, primitives)
  1832.      creates FILENAME as a PDB file in "w+b" mode, destroying any
  1833.      existing file by that name.  If the PRIMITIVES argument is
  1834.      supplied, it must be the name of a procedure that sets the
  1835.      primitive data types for the file.  The default is to create
  1836.      a file with the native primitive types of the machine on which
  1837.      Yorick is running.  The following PRIMITIVES functions are
  1838.      predefined:
  1839.         sun_primitives    -- appropriate for Sun, HP, IBM, and
  1840.                          most other workstations
  1841.         sun3_primitives   -- appropriate for old Sun-2 or Sun-3
  1842.         dec_primitives    -- appropriate for DEC (MIPS) workstations
  1843.         alpha_primitives  -- appropriate for DEC alpha workstations
  1844.         cray_primitives   -- appropriate for Cray 1, XMP, and YMP
  1845.     mac_primitives    -- appropriate for MacIntosh
  1846.     macl_primitives   -- appropriate for MacIntosh, 12-byte double
  1847.     pc_primitives     -- appropriate for IBM PC
  1848.         vax_primitives    -- appropriate for VAXen only (H doubles)
  1849.         vaxg_primitives   -- appropriate for VAXen only (G doubles)
  1850.         xdr_primitives    -- appropriate for XDR files
  1851.   SEE ALSO: openb, updateb, cd
  1852.             save, add_record, set_filesize, set_blocksize
  1853.         close102, close102_default, at_pdb_open, at_pdb_close
  1854.  */
  1855. {
  1856.   file= open(filename, "w+b");
  1857.   if (!is_void(primitives)) primitives, file;
  1858.   if (!is_void(close102)) yPDBclose= ((close102&1)|(at_pdb_close&~1));
  1859.   else if (is_void(close102_default)) yPDBclose= at_pdb_close;
  1860.   else yPDBclose= ((close102_default&1)|(at_pdb_close&~1));
  1861.   _init_pdb, file, yPDBclose;
  1862.   return file;
  1863. }
  1864.  
  1865. func sun_primitives(file)
  1866. /* DOCUMENT sun_primitives, file
  1867.      sets FILE primitive data types to be native to Sun, HP, IBM, etc.
  1868.  */
  1869. {
  1870.   require, "prmtyp.i";
  1871.   raw_sun_p, file;
  1872. }
  1873.  
  1874. func sun3_primitives(file)
  1875. /* DOCUMENT sun3_primitives, file
  1876.      sets FILE primitive data types to be native to Sun-2 or Sun-3.
  1877.  */
  1878. {
  1879.   require, "prmtyp.i";
  1880.   raw_sun3_p, file;
  1881. }
  1882.  
  1883. func dec_primitives(file)
  1884. /* DOCUMENT dec_primitives, file
  1885.      sets FILE primitive data types to be native to DEC (MIPS) workstations.
  1886.  */
  1887. {
  1888.   require, "prmtyp.i";
  1889.   raw_dec_p, file;
  1890. }
  1891.  
  1892. func alpha_primitives(file)
  1893. /* DOCUMENT alpha_primitives, file
  1894.      sets FILE primitive data types to be native to DEC alpha workstations.
  1895.  */
  1896. {
  1897.   require, "prmtyp.i";
  1898.   raw_alpha_p, file;
  1899. }
  1900.  
  1901. func cray_primitives(file)
  1902. /* DOCUMENT cray_primitives, file
  1903.      sets FILE primitive data types to be native to Cray 1, XMP, and YMP.
  1904.  */
  1905. {
  1906.   require, "prmtyp.i";
  1907.   raw_cray_p, file;
  1908. }
  1909.  
  1910. func mac_primitives(file)
  1911. /* DOCUMENT mac_primitives, file
  1912.      sets FILE primitive data types to be native to MacIntosh, 8 byte double.
  1913.  */
  1914. {
  1915.   require, "prmtyp.i";
  1916.   raw_mac_p, file;
  1917. }
  1918.  
  1919. func macl_primitives(file)
  1920. /* DOCUMENT macl_primitives, file
  1921.      sets FILE primitive data types to be native to MacIntosh, long double.
  1922.  */
  1923. {
  1924.   require, "prmtyp.i";
  1925.   raw_macl_p, file;
  1926. }
  1927.  
  1928. func pc_primitives(file)
  1929. /* DOCUMENT pc_primitives, file
  1930.      sets FILE primitive data types to be native to IBM PC.
  1931.  */
  1932. {
  1933.   require, "prmtyp.i";
  1934.   raw_pc_p, file;
  1935. }
  1936.  
  1937. func vax_primitives(file)
  1938. /* DOCUMENT vax_primitives, file
  1939.      sets FILE primitive data types to be native to VAXen, H-double, only.
  1940.  */
  1941. {
  1942.   require, "prmtyp.i";
  1943.   raw_vax_p, file;
  1944. }
  1945.  
  1946. func vaxg_primitives(file)
  1947. /* DOCUMENT vaxg_primitives, file
  1948.      sets FILE primitive data types to be native to VAXen, G-double, only.
  1949.  */
  1950. {
  1951.   require, "prmtyp.i";
  1952.   raw_vaxg_p, file;
  1953. }
  1954.  
  1955. func xdr_primitives(file)
  1956. /* DOCUMENT xdr_primitives, file
  1957.      sets FILE primitive data types to be XDR (external data representation).
  1958.  */
  1959. {
  1960.   require, "prmtyp.i";
  1961.   raw_xdr_p, file;
  1962. }
  1963.  
  1964. func updateb(filename, primitives, close102=, open102=)
  1965. /* DOCUMENT file= updateb(filename)
  1966.          or file= updateb(filename, primitives)
  1967.      open a binary date file FILENAME for update (mode "r+b").
  1968.      The optional PRIMITIVES argument is as for the createb function.
  1969.      If the file exists, it is opened as if by openb(filename),
  1970.      otherwise a new PDB file is created as if by createb(filename).
  1971.    SEE ALSO: openb, createb, cd, save, restore, get_vars, get_addrs
  1972.              close102, close102_default, open102, at_pdb_open, at_pdb_close
  1973.  */
  1974. {
  1975.   if (is_void(open(filename, "r", 1)))   /* "rb" does much more work */
  1976.     return createb(filename, primitives, close102=close102);
  1977.   else
  1978.     return openb(filename,,1, open102=open102);
  1979. }
  1980.  
  1981. extern save;
  1982. extern restore;
  1983. /* DOCUMENT save, file, var1, var2, ...
  1984.             restore, file, var1, var2, ...
  1985.      saves the variables VAR1, VAR2, etc. in the binary file FILE,
  1986.      or restores them from that file.
  1987.      The VARi may be either non-record or record data in the case that
  1988.      FILE contains records.
  1989.  
  1990.      If one of the VARi does not already exist in FILE, it is created
  1991.      by the save command; after add_record, save adds or stores VARi to
  1992.      the current record.  See add_record for more.  The VARi may be
  1993.      structure definitions (for the save command) to declare data
  1994.      structures for the file.  This is necessary only in the case that
  1995.      a record variable is a pointer -- all of the potential data types
  1996.      of pointees must be known.  No data structures may be declared
  1997.      using the save command after the first record has been added.
  1998.  
  1999.      If no VARi are present, save saves all array variables, and
  2000.      restore restores every non-record variable in the file if there
  2001.      is no current record, and every variable in the current record if
  2002.      there is one.
  2003.    SEE ALSO: openb, createb, updateb, get_vars, add_record, get_addrs
  2004.              jt, jc, _read, _write, data_align
  2005.  */
  2006.  
  2007. func jt(file, time)
  2008. /* DOCUMENT jt, time
  2009.          or jt, file, time
  2010.          or jt, file
  2011.          or jt, file, -
  2012.      jump to the record nearest the specified TIME.  If no FILE is
  2013.      specified, the current record of all open binary files containing
  2014.      records is shifted.
  2015.      If both FILE and TIME are specified and jt is called as a function,
  2016.      it returns the actual time of the new current record.
  2017.  
  2018.    N.B.: "jt, file" and "jt, file, -" are obsolete.  Use the jr function to
  2019.      step through a file one record at a time.
  2020.  
  2021.      If only the FILE is specified, increment the current record of that
  2022.      FILE by one.  If the TIME argument is - (the pseudo-index range
  2023.      function), decrement the current record of FILE by one.
  2024.      If the current record is the last, "jt, file" unsets the current record
  2025.      so that record variables will be inaccessible until another jt or jc.
  2026.      The same thing happens with "jt, file, -" if the current record was the
  2027.      first.
  2028.      If only FILE is specified, jt returns 1 if there is a new current
  2029.      record, 0 if the call resulted in no current record.  Thus "jt(file)"
  2030.      and "jt(file,-)" may be used as the condition in a while loop to step
  2031.      through every record in a file:
  2032.         file= openb("example.pdb");
  2033.         do {
  2034.       restore, file, interesting_record_variables;
  2035.       ...calculations...
  2036.     } while (jt(file));
  2037.  
  2038.    SEE ALSO: jc, _jt, edit_times, show, jr
  2039.  */
  2040. {
  2041.   return is_void(time)? _jt(file) : _jt(file, time);
  2042. }
  2043.  
  2044. func jc(file, ncyc)
  2045. /* DOCUMENT jc, file, ncyc
  2046.      jump to the record of FILE nearest the specified NCYC.
  2047.    SEE ALSO: jt, _jc, edit_times, show, jr
  2048.  */
  2049. {
  2050.   return _jc(file, ncyc);
  2051. }
  2052.  
  2053. extern _jr;
  2054. extern _jt;
  2055. extern _jc;
  2056. /* DOCUMENT _jt, file, time
  2057.             _jc, file, ncyc
  2058.         _jr, file
  2059.      are raw versions of jt and jc provided to simplify redefining
  2060.      the default jt and jc functions to add additional features.
  2061.      For example, you could redefine jt to jump to a time, then
  2062.      plot something.  The new jt can pass its arguments along to
  2063.      _jt, then call the appropriate plotting functions.
  2064.      There is a raw version of jr as well.
  2065.  */
  2066.  
  2067. func jr(file, i)
  2068. /* DOCUMENT jr, file, i
  2069.          or _jr(file, i)
  2070.      Jump to a particular record number I (from 1 to n_records) in a
  2071.      binary file FILE.  The function returns 1 if such a record exists,
  2072.      0 if there is no such record.  In the latter case, no action is
  2073.      taken; the program halts with an error only if jr was invoked
  2074.      as a subroutine.  Record numbering wraps like array indices; use
  2075.      jr, file, 0  to jump to the last record, -1 to next to last, etc.
  2076.    SEE ALSO: jt, jc, edit_times, show
  2077.  */
  2078. {
  2079.   return _jr(file, i);
  2080. }
  2081.  
  2082. extern add_record;
  2083. /* DOCUMENT add_record, file, time, ncyc
  2084.          or add_record, file, time, ncyc, address
  2085.          or add_record, file
  2086.      adds a new record to FILE corresponding to the specified TIME and
  2087.      NCYC (respectively a double and a long).  Either or both TIME
  2088.      and NCYC may be nil or omitted, but the existence of TIME and
  2089.      NCYC must be the same for every record added to one FILE.
  2090.      If present, ADDRESS specifies the disk address of the new record,
  2091.      which is assumed to be in the current file.  Without ADDRESS, or
  2092.      if ADDRESS<0, the next available address is used; this may create
  2093.      a new file in the family (see the set_filesize function).
  2094.      The add_record function leaves the new record current
  2095.      for subsequent save commands to actually write the data.
  2096.  
  2097.      The TIME, NCYC, and ADDRESS arguments may be equal length vectors
  2098.      to add several records at once; in this case, the first of the
  2099.      newly added records is the current one.  If all three of TIME,
  2100.      NCYC, and ADDRESS are nil or omitted, no new records are added,
  2101.      but the file becomes a record file if it was not already, and in
  2102.      any case, no record will be the current record after such an
  2103.      add_record call.
  2104.  
  2105.      After the first add_record call (even if no records were added),
  2106.      subsequent add_variable commands will create record variables.
  2107.      After the first record has been added, subsequent save commands
  2108.      will create any new variables as record variables.
  2109.      After a second record has been added using add_record, neither
  2110.      save commands nor add_variable commands may be used to introduce
  2111.      any new record variables.
  2112.    SEE ALSO: save, createb, updateb, openb, set_filesize, set_blocksize
  2113.              add_variable
  2114.  */
  2115.  
  2116. extern add_variable;
  2117. /* DOCUMENT add_variable, file, address, name, type, dimlist
  2118.      adds a variable NAME to FILE at the specified ADDRESS, with the
  2119.      specified TYPE and dimensions given by DIMLIST.  The DIMLIST may
  2120.      be zero or more arguments, as for the "array" function.  If the
  2121.      ADDRESS is <0, the next available address is used. Note that,
  2122.      unlike the save command, add_variable does not actually write any
  2123.      data -- it merely changes Yorick's description of the contents of
  2124.      FILE.
  2125.      After the first add_record call, add_variable adds a variable to
  2126.      the record instead of a non-record variable.  See add_record.
  2127.    SEE ALSO: save, openb, createb, updateb, add_record,
  2128.              add_member, install_struct, data_align
  2129.  */
  2130.  
  2131. extern set_blocksize;
  2132. /* DOCUMENT set_blocksize, file, blocksize
  2133.      sets smallest cache block size for FILE to BLOCKSIZE.  BLOCKSIZE
  2134.      is rounded to the next larger number of the form 4096*2^n if
  2135.      necessary; cache blocks for this file will be multiples of
  2136.      BLOCKSIZE bytes long.  The default BLOCKSIZE is 0x4000 (16 KB).
  2137.    SEE ALSO: openb, updateb, createb, save, restore, _read, _write
  2138.  */
  2139.  
  2140. extern set_filesize;
  2141. /* DOCUMENT set_filesize, file, filesize
  2142.      sets the new family member threshhold for FILE to FILESIZE.
  2143.      Whenever a new record is added (see add_record), if the current file
  2144.      in the FILE family has at least one record and the new record would
  2145.      cause the current file to exceed FILESIZE bytes, a new family
  2146.      member will be created to hold the new record.
  2147.      The default FILESIZE is 0x400000 (4 MB).
  2148.    SEE ALSO: openb, updateb, createb, add_record
  2149.  */
  2150.  
  2151. extern get_vars;
  2152. /* DOCUMENT name_lists= get_vars(file)
  2153.      returns the lists of non-record and record variable names in the
  2154.      binary FILE.  The return value is an array of two pointers to
  2155.      arrays of type string; *name_lists(1) is the array of non-record
  2156.      variable names (or nil if there are none), *name_lists(2) is the
  2157.      array of record variable names.
  2158.      The get_addrs function returns corresponding lists of disk
  2159.      addresses; the get_member function can be used in conjunction
  2160.      with the dimsof, structof, and typeof functions to determine
  2161.      the other properties of a variable.
  2162.    SEE ALSO: openb, updateb, restore, jt, jc, has_records, get_addrs
  2163.  */
  2164.  
  2165. extern get_addrs;
  2166. /* DOCUMENT addr_lists= get_addrs(file)
  2167.      returns the byte addresses of the non-record and record variables
  2168.      in the binary file FILE, and lists of the record addresses, file
  2169.      indices, and filenames for file families with history records.
  2170.           *addr_lists(1)   absolute addresses of non-record variables
  2171.       *addr_lists(2)   relative addresses of record variables
  2172.                        (add record address to get absolute address)
  2173.          The order of these two address lists matches the
  2174.          corresponding lists of names returned by get_vars.
  2175.       *addr_lists(3)   absolute addresses of records
  2176.       *addr_lists(4)   list of file indices corresponding to
  2177.                        addr_lists(3); indices are into addr_lists(5)
  2178.       *addr_lists(5)   list of filenames in the family
  2179.    SEE ALSO: openb, updateb, restore, jt, jc, has_records, get_vars
  2180.  */
  2181.  
  2182. func has_records(file)
  2183. /* DOCUMENT has_records(file)
  2184.      returns 1 if FILE has history records, 0 if it does not.
  2185.  */
  2186. {
  2187.   return get_vars(file)(2)? 1n : 0n;
  2188. }
  2189.  
  2190. extern get_times;
  2191. extern get_ncycs;
  2192. /* DOCUMENT times= get_times(file)
  2193.             ncycs= get_ncycs(file)
  2194.      returns the list of time or ncyc values associated with the records
  2195.      if FILE, or nil if there are none.  The time values are not guaranteed
  2196.      to be precise (but they should be good to at least 6 digits or so);
  2197.      the precise time associated with each record may be stored as a record
  2198.      variable.
  2199.    SEE ALSO: collect, openb, updateb, restore, jt, jc, edit_times
  2200.  */
  2201.  
  2202. extern edit_times;
  2203. /* DOCUMENT edit_times, file
  2204.          or edit_times, file, keep_list
  2205.          or edit_times, file, keep_list, new_times, new_ncycs
  2206.      edits the records for FILE.  The KEEP_LIST is a 0-origin index list
  2207.      of records to be kept, or nil to keep all records.  The NEW_TIMES
  2208.      array is the list of new time values for the (kept) records, and
  2209.      the NEW_NCYCS array is the list of new cycle number values for the
  2210.      (kept) records.  Either NEW_TIMES, or NEW_NCYCS, or both, may be
  2211.      nil to leave the corresponding values unchanged.  If non-nil,
  2212.      NEW_TIMES and NEW_NCYCS must have the same length as KEEP_LIST,
  2213.      or, if KEEP_LIST is nil, as the original number of records in
  2214.      the file.  If KEEP_LIST, NEW_TIME, and NEW_NCYCS are all omitted
  2215.      or nil, then edit_times removes records as necessary to ensure
  2216.      that the remaining records have monotonically increasing times,
  2217.      or, if no times are present, monotonically increasing ncycs.
  2218.      (The latest record at any given time/ncyc is retained, and earlier
  2219.      records are removed.)
  2220.      In no case does edit_times change the FILE itself; only Yorick's
  2221.      in-memory model of the file is altered.
  2222.    SEE ALSO: get_times, get_ncycs, jt, jc
  2223.  */
  2224.  
  2225. extern _read;
  2226. extern _write;
  2227. /* DOCUMENT _write, file, address, expression
  2228.             _read, file, address, variable
  2229.      or nbytes= _read(file, address, variable);
  2230.      are low level read and write functions which do not "see" the
  2231.      symbol table for the binary FILE.  The ADDRESS is the byte address
  2232.      at which to begin the write or read operation.  The type and number
  2233.      of objects of the EXPRESSION or VARIABLE determines how much data
  2234.      to read, and what format conversion operations to apply.  In the
  2235.      case of type char, no conversion operations are ever applied, and
  2236.      _read will return the actual number of bytes read, which may be
  2237.      fewer than the number implied by VARIABLE in this one case.
  2238.      (In all other cases, _read returns numberof(VARIABLE).)
  2239.      If the FILE has records, the ADDRESS is understood to be in the
  2240.      file family member in which the current record resides.
  2241.    SEE ALSO: openb, createb, updateb, save, restore, sizeof
  2242.  */
  2243.  
  2244. extern add_member;
  2245. /* DOCUMENT add_member, file, struct_name, offset, name, type, dimlist
  2246.      adds a member to a data type in the file FILE.  The data type name
  2247.      (struct name) is STRUCT_NAME, which will be created if it does
  2248.      not already exist.  The new member will be at OFFSET (in bytes)
  2249.      from the beginning of an instance of this structure, and will
  2250.      have the specified NAME, TYPE, and DIMLIST.  Use OFFSET -1 to
  2251.      have add_member compute the next available offset in the structure.
  2252.      The TYPE can be either a structure definition, or a string naming
  2253.      a previously defined data type in FILE.  The optional DIMLIST is
  2254.      as for the "array" function.
  2255.      The STRUCT_NAME built from a series of add_member calls cannot be
  2256.      used until it is installed with install_struct.
  2257.      This function should be used very sparingly, mostly in code which
  2258.      is building the structure of a foreign-format binary file.
  2259.    SEE ALSO: add_variable, install_struct, struct_align
  2260.  */
  2261.  
  2262. extern install_struct;
  2263. /* DOCUMENT install_struct, file, struct_name
  2264.          or install_struct, file, struct_name, size, align, order
  2265.          or install_struct, file, struct_name, size, align, order, layout
  2266.      installs the data type named STRUCT_NAME in the binary FILE.  In
  2267.      the two argument form, STRUCT_NAME must have been built by one or
  2268.      more calls to the add_member function.  In the 5 and 6 argument calls,
  2269.      STRUCT_NAME is a primitive data type -- an integer type for the 5
  2270.      argument call, and a floating point type for the 6 argument call.
  2271.      The 5 argument form may also be used to declare opaque data types.
  2272.      SIZE is the size of an instance in bytes, ALIGN is its alignment
  2273.      boundary (also in bytes), and ORDER is the byte order.  ORDER is
  2274.      1 for most significant byte first, -1 for least significant byte
  2275.      first, and 0 for opaque (unconverted) data.  Other ORDER values
  2276.      represent more complex byte permutations (2 is the byte order for
  2277.      VAX floating point numbers).  If ORDER equals SIZE, then the data
  2278.      type is not only opaque, but also must be read sequentially.
  2279.      LAYOUT is an array of 7 long values parameterizing the floating
  2280.      point format, [sign_address, exponent_address, exponent_size,
  2281.      mantissa_address, mantissa_size, mantissa_normalized, exponent_bias]
  2282.      (the addresses and sizes are in bits, reduced to MSB first order).
  2283.      Use, e.g., nameof(float) for STRUCT_NAME to redefine the meaning
  2284.      of the float data type for FILE.
  2285.    SEE ALSO: add_variable, add_member
  2286.  */
  2287.  
  2288. extern data_align;
  2289. /* DOCUMENT data_align, file, alignment
  2290.      in binary file FILE, align new variables to begin at a byte address
  2291.      which is a multiple of ALIGNMENT.  (This affects placement of data
  2292.      declared using save and add_variable.  For add_variable, data_align
  2293.      has an effect only if the address is not specified.)  If ALIGNMENT
  2294.      is <=0, new variables will be aligned as they would be if they were
  2295.      data structure members.  The default value is 0.
  2296.    SEE ALSO: save, add_variable
  2297.  */
  2298.  
  2299. extern struct_align;
  2300. /* DOCUMENT struct_align, file, alignment
  2301.      in binary file FILE, align new struct members which are themselves
  2302.      struct instances to begin at a byte address which is a multiple of
  2303.      ALIGNMENT.  (This affects members declared explicitly by add_member,
  2304.      as well as implicitly by save or add_variable.)  If ALIGNMENT is <=0,
  2305.      returns to the default for this machine.  The struct alignment is in
  2306.      addition to the alignment implied by the most restrictively aligned
  2307.      member of the struct.  Most machines want ALIGNMENT of 1.
  2308.    SEE ALSO: add_member
  2309.  */
  2310.  
  2311. extern add_next_file;
  2312. /* DOCUMENT failure= add_next_file(file, filename, create_flag)
  2313.      adds the next file to the FILE, which must contain history records.
  2314.      If FILENAME is non-nil, the new file will be called that, otherwise
  2315.      the next sequential filename is used.  If CREATE_FLAG is present
  2316.      and non-zero, the new file will be created if it does not already
  2317.      exist.  If omitted or nil, CREATE_FLAG defaults to 1 if the file has
  2318.      write permission and 0 if it does not.
  2319.      Returns 0 on success.
  2320.    SEE ALSO: openb, updateb, createb, add_record
  2321.  */
  2322.  
  2323. /*--------------------------------------------------------------------------*/
  2324.  
  2325. extern error;
  2326. extern exit;
  2327. /* DOCUMENT exit, msg
  2328.             error, msg
  2329.      Exits the current interpreted *main* program, printing the MSG.
  2330.      (MSG can be omitted to print a default.)
  2331.      In the case of exit, the result is equivalent to an immediate
  2332.      return from every function in the current calling chain.
  2333.      In the case of error, the result is the same as if an error had
  2334.      occurred in a compiled routine.
  2335.    SEE ALSO: print, write, batch, catch
  2336.  */
  2337.  
  2338. extern catch;
  2339. /* DOCUMENT catch(category)
  2340.      Catch errors of the specified category.  Category may be -1 to
  2341.      catch all errors, or a bitwise or of the following bits:
  2342.  
  2343.         0x01 math errors (SIGFPE, math library)
  2344.     0x02 I/O errors
  2345.     0x04 keyboard interrupts (e.g.- control C interrupt)
  2346.     0x08 other compiled errors (YError)
  2347.     0x10 interpreted errors (error)
  2348.  
  2349.      Use catch by placing it in a function before the section of code
  2350.      in which you are trying to catch errors.  When catch is called,
  2351.      it always returns 0, but it records the virtual machine program
  2352.      counter where it was called, and longjumps there if an error is
  2353.      detected.  The most recent matching call to catch will catch the
  2354.      error.  Returning from the function in which catch was called
  2355.      pops that call off the list of catches the interpreter checks.
  2356.  
  2357.      To use catch, place the call near the top of a function:
  2358.  
  2359.         if (catch(category)) {
  2360.       ...<code to execute if error is caught>...
  2361.     }
  2362.         ...<code "protected" by the catch>...
  2363.  
  2364.      If an error with the specified category occurs in the "protected"
  2365.      code, the program jumps back to the point of the catch and acts
  2366.      as if the catch function had returned 1 (remember that when catch
  2367.      is actually called it always returns 0).
  2368.  
  2369.      In order to lessen the chances of infinite loops, the catch is
  2370.      popped off the active list if it is actually used, so that a
  2371.      second error will *not* be caught.  Often, this is only desirable
  2372.      for the error handling code itself -- if you want to re-execute
  2373.      the "protected" code, do this, and take care of the possibility
  2374.      of infinite loops in your interpreted code:
  2375.  
  2376.         while (catch(category)) {
  2377.       ...<code to execute if error is caught>...
  2378.     }
  2379.         ...<code "protected" by the catch>...
  2380.  
  2381.      After an error has been caught, the associated error message
  2382.      (what would have been printed had it not been caught) is left
  2383.      in the variable catch_message.
  2384.  
  2385.    SEE ALSO: error
  2386.  */
  2387.  
  2388. extern batch;
  2389. /* DOCUMENT batch, 1
  2390.             batch, 0
  2391.         batch()
  2392.      turns on, turns off, or tests for batch mode, respectively.
  2393.      If yorick is started with the command line:
  2394.         yorick -batch batch_include.i ...
  2395.      then batch mode is turned on, the usual custom.i startup file is
  2396.      skipped, and the file batch_include.i is parsed and executed.  The
  2397.      -batch and batch_include.i command line arguments are removed from
  2398.      the list returned by get_argv().  These must be the first two
  2399.      arguments on the command line.
  2400.  
  2401.      In batch mode, any error will terminate Yorick (as by the quit
  2402.      function) rather than entering debug mode.
  2403.  
  2404.    SEE ALSO: process_argv, get_argv, set_idler
  2405.  */
  2406.  
  2407. extern set_idler;
  2408. /* DOCUMENT set_idler, idler_function
  2409.      sets the idler function to IDLER_FUNCTION.  Instead of waiting
  2410.      for keyboard input when all its tasks are finished, the interpreter
  2411.      will invoke IDLER_FUNCTION with no arguments.  The idler function
  2412.      is normally invoked only once, so input from the keyboard resumes
  2413.      after one call to the idler.  Of course, an idler is free to call
  2414.      set_idler again before it returns, which will have the effect of
  2415.      calling that function in a loop.
  2416.    SEE ALSO: batch
  2417.  */
  2418.  
  2419. /*--------------------------------------------------------------------------*/
  2420.  
  2421. extern timestamp;
  2422. /* DOCUMENT timestamp()
  2423.      returns string of the form "Sun Jan  3 15:14:13 1988" -- always
  2424.      has 24 characters.
  2425.    SEE ALSO: timer
  2426.  */
  2427.  
  2428. extern timer;
  2429. /* DOCUMENT timer, elapsed
  2430.          or timer, elapsed, split
  2431.      updates the ELAPSED and optionally SPLIT timing arrays.  These
  2432.      arrays must each be of type array(double,3); the layout is
  2433.      [cpu, system, wall], with all three times measured in seconds.
  2434.      ELAPSED is updated to the total times elapsed since this copy
  2435.      of Yorick started.  SPLIT is incremented by the difference between
  2436.      the new values of ELAPSED and the values of ELAPSED on entry.
  2437.      This feature allows for primitive code profiling by keeping
  2438.      separate accounting of time usage in several categories, e.g.--
  2439.         elapsed= total= cat1= cat2= cat3= array(double, 3);
  2440.         timer, elapsed0;
  2441.     elasped= elapsed0;
  2442.         ... category 1 code ...
  2443.     timer, elapsed, cat1;
  2444.         ... category 2 code ...
  2445.     timer, elapsed, cat2;
  2446.         ... category 3 code ...
  2447.     timer, elapsed, cat3;
  2448.         ... more category 2 code ...
  2449.     timer, elapsed, cat2;
  2450.         timer, elapsed0, total;
  2451.      The wall time is not absolutely reliable, owning to possible
  2452.      rollover at midnight.
  2453.    SEE ALSO: timestamp, timer_print
  2454.  */
  2455.  
  2456. func timer_print(label, split, ..)
  2457. /* DOCUMENT timer_print, label1, split1, label2, split2, ...
  2458.          or timer_print
  2459.          or timer_print, label_total
  2460.      prints out a timing summary for splits accumulated by timer.
  2461.         timer_print, "category 1", cat1, "category 2", cat2,
  2462.                      "category 3", cat3, "total", total;
  2463.    SEE ALSO: timer
  2464.  */
  2465. {
  2466.   elapsed= s= array(double, 1:3);
  2467.   timer, elapsed;
  2468.   write,format="%30s     CPU sec  System sec    Wall sec\n","Timing Category";
  2469.   if (!is_void(label) && !is_void(split)) {
  2470.     s(1:3)= split;
  2471.     write,format="%30s %11.3f %11.3f %11.3f\n", label, s(1), s(2), s(3);
  2472.   }
  2473.   while (more_args()>1) {
  2474.     labl= next_arg();
  2475.     s(1:3)= next_arg();
  2476.     write,format="%30s %11.3f %11.3f %11.3f\n", labl, s(1), s(2), s(3);
  2477.   }
  2478.   if (is_void(label) || is_void(split)) {
  2479.     if (is_void(label)) labl= "-----Total Elapsed Times-----";
  2480.     else labl= label;
  2481.     s(1:3)= elapsed;
  2482.     write,format="%30s %11.3f %11.3f %11.3f\n", labl, s(1), s(2), s(3);
  2483.   }
  2484. }
  2485.  
  2486. _timer_elapsed= [0.,0.,0.];
  2487. timer, _timer_elapsed;
  2488.  
  2489. /*--------------------------------------------------------------------------*/
  2490.  
  2491. func area(y, x)
  2492. /* DOCUMENT area(y, x)
  2493.      returns the zonal areas of the 2-D mesh (X, Y).  If Y and X are
  2494.      imax-by-jmax, the result is (imax-1)-by-(jmax-1).  The area is
  2495.      positive when, say, X increases with i and Y increases with j.
  2496.      For example, area([[0,0],[1,1]],[[0,1],[0,1]]) is +1.
  2497.    SEE ALSO: volume
  2498.  */
  2499. { return x(dif,zcen)*y(zcen,dif) - x(zcen,dif)*y(dif,zcen); }
  2500.  
  2501. func volume(r, z)
  2502. /* DOCUMENT volume(r, z)
  2503.      returns the zonal volumes of the 2-D cylindrical mesh (R, Z).
  2504.      If R and Z are imax-by-jmax, the result is (imax-1)-by-(jmax-1).
  2505.      The volume is positive when, say, Z increases with i and R increases
  2506.      with j.  For example, volume([[0,0],[1,1]],[[0,1],[0,1]]) is +pi.
  2507.    SEE ALSO: area
  2508.  */
  2509. {
  2510.   s= r*r;
  2511.   v= z(dif,zcen)*s(zcen,dif) - z(zcen,dif)*s(dif,zcen);
  2512.   s= z*r;
  2513.   return (2.0*pi/3.0)*(v+s(dif,zcen)*r(zcen,dif)-s(zcen,dif)*r(dif,zcen));
  2514. }
  2515.  
  2516. func ptcen(zncen, ireg)
  2517. /* DOCUMENT ptcen(zncen)
  2518.          or ptcen(zncen, ireg)
  2519.      returns point centered version of the 2-D zone centered array ZNCEN.
  2520.      The result is imax-by-jmax if ZNCEN is (imax-1)-by-(jmax-1).
  2521.      If the region number array IREG is specified, zones with region
  2522.      number 0 are not included in the point centering operation.
  2523.      Note that IREG should have dimensions imax-by-jmax; the first
  2524.      row and column of IREG are ignored.
  2525.      Without IREG, ptcen(zncen) is equivalent to zncen(pcen,pcen).
  2526.   SEE ALSO: zncen, uncen
  2527.  */
  2528. {
  2529.   if (is_void(ireg)) return zncen(pcen, pcen, ..);
  2530.   void= use_origins(0);
  2531.   exist= (ireg(2:,2:)!=0);
  2532.   return (exist*zncen)(pcen,pcen,..)/(exist(pcen,pcen)+1.e-35);
  2533. }
  2534.  
  2535. func zncen(ptcen, ireg)
  2536. /* DOCUMENT zncen(ptcen)
  2537.          or zncen(ptcen, ireg)
  2538.      returns zone centered version of the 2-D point centered array PTCEN.
  2539.      The result is (imax-1)-by-(jmax-1) if PTCEN is imax-by-jmax.
  2540.      If the region number array IREG is specified, zones with region
  2541.      number 0 are not included in the point centering operation.
  2542.      Note that IREG should have dimensions imax-by-jmax, like
  2543.      the input PTCEN array; the first row and column of IREG are ignored.
  2544.      Without IREG, zncen(ptcen) is equivalent to ptcen(zcen,zcen).
  2545.   SEE ALSO: ptcen, uncen
  2546.  */
  2547. {
  2548.   if (is_void(ireg)) return ptcen(zcen, zcen, ..);
  2549.   void= use_origins(0);
  2550.   exist= (ireg(2:,2:)!=0);
  2551.   return exist*ptcen(zcen, zcen, ..);
  2552. }
  2553.  
  2554. func uncen(ptcen, ireg)
  2555. /* DOCUMENT uncen(ptcen)
  2556.          or uncen(ptcen, ireg)
  2557.      returns zone centered version of the 2-D zone centered array PTCEN.
  2558.      The result is (imax-1)-by-(jmax-1) if PTCEN is imax-by-jmax.
  2559.      If the region number array IREG is specified, zones with region
  2560.      number 0 are not included in the point centering operation.
  2561.      Note that IREG should have dimensions imax-by-jmax, like
  2562.      the input PTCEN array; the first row and column of IREG are ignored.
  2563.      Without IREG, uncen(ptcen) is equivalent to ptcen(uncp,uncp).
  2564.  
  2565.      Do not use uncen to zone center data which is naturally point
  2566.      centered -- use the zncen function for that purpose.  The uncen
  2567.      function is the (nearly) exact inverse of the ptcen function,
  2568.      so that uncen(ptcen(zncen, ireg), ireg) will return the original
  2569.      zncen array.  The uncen reconstruction is as exact as possible,
  2570.      given the finite precision of floating point operations.
  2571.   SEE ALSO: ptcen, zncen
  2572.  */
  2573. {
  2574.   if (is_void(ireg)) return ptcen(uncp, uncp, ..);
  2575.   void= use_origins(0);
  2576.   exist= (ireg(2:,2:)!=0);
  2577.   return (exist(pcen,pcen)*ptcen)(uncp, uncp, ..);
  2578. }
  2579.  
  2580. /*--------------------------------------------------------------------------*/
  2581.  
  2582. func call(void)
  2583. /* DOCUMENT call, subroutine(arg1, arg2, arg3, arg4, arg5
  2584.                              arg6, arg7, arg8);
  2585.      allows a SUBROUTINE to be called with a very long argument list
  2586.      as an alternative to:
  2587.           subroutine, arg1, arg2, arg3, arg4, arg5,
  2588.             arg6, arg7, arg8;
  2589.      Note that the statement
  2590.           subroutine(arg1, arg2, arg3, arg4, arg5,
  2591.                      arg6, arg7, arg8);
  2592.      will print the return value of subroutine, even if it is nil.
  2593.      If invoked as a function, call simply returns its argument.
  2594.  */
  2595. { return void; }
  2596.  
  2597. extern symbol_def;
  2598. /* DOCUMENT symbol_def(func_name)(arglist)
  2599.          or symbol_def(var_name)
  2600.      invokes the function FUNC_NAME with the specified ARGLIST,
  2601.      returning the return value.  ARGLIST may be zero or more arguments.
  2602.      In fact, symbol_def("fname")(arg1, arg2, arg3) is equivalent to
  2603.      fname(arg1, arg2, arg3), so that "fname" can be the name of any
  2604.      variable for which the latter syntax is meaningful -- interpreted
  2605.      function, built-in function, or array.
  2606.  
  2607.      Without an argument list, symbol_def("varname") is equivalent to
  2608.      varname, which allows you to get the value of a variable whose name
  2609.      you must compute.
  2610.  
  2611.      DO NOT OVERUSE THIS FUNCTION.  It works around a specific deficiency
  2612.      of the Yorick language -- the lack of pointers to functions -- and
  2613.      should be used for such purposes as hook lists (see openb).
  2614.  
  2615.    SEE ALSO: symbol_set
  2616.  */
  2617.  
  2618. extern symbol_set;
  2619. /* DOCUMENT symbol_set, var_name, value
  2620.      is equivalent to the redefinition
  2621.           varname= value
  2622.      except that var_name="varname" is a string which must be computed.
  2623.  
  2624.      DO NOT OVERUSE THIS FUNCTION.  It works around a specific deficiency
  2625.      of the Yorick language -- the lack of pointers to functions, streams,
  2626.      bookmarks, and other special non-array data types.
  2627.  
  2628.    SEE ALSO: symbol_def
  2629.  */
  2630.  
  2631. /*--------------------------------------------------------------------------*/
  2632.  
  2633. extern dbexit;
  2634. extern dbcont;
  2635. extern dbret;
  2636. extern dbskip;
  2637. extern dbup;
  2638. extern dbinfo;
  2639. extern dbdis;
  2640. extern dbauto;
  2641. /* DOCUMENT Debug mode.
  2642.  
  2643.    Yorick errors fall into two general categories: Syntax errors discovered
  2644.    during parsing, and runtime errors discovered when a Yorick program is
  2645.    actually running.  When a runtime error occurs, Yorick offers the
  2646.    choice of entering "debug mode", which you can do by typing the <RETURN>
  2647.    key immediately after the error occurs.  Typing a non-blank line exits
  2648.    debug mode automatically by default.  In debug mode, the Yorick prompt
  2649.    becomes "dbug>" instead of the usual ">".  When you see this prompt,
  2650.    Yorick has halted "in the middle of" the function in which the error
  2651.    occurred, and you can print, plot, modify, or save the local variables
  2652.    in that function by means of ordinary Yorick commands.  Debug mode is
  2653.    recursive; that is, you can debug an error which occurred during
  2654.    debugging to any number of levels.
  2655.  
  2656.    You can exit from debug mode in several ways:
  2657.  
  2658.       dbexit            -- exit current debug level, discarding all
  2659.                            active functions and their local variables
  2660.       dbexit, 0         -- exit all debug levels
  2661.       dbexit, n         -- exit (at most) N debug levels
  2662.  
  2663.       dbcont            -- continue execution of the current function
  2664.          Continuing is useful if you have managed to repair the
  2665.      problem which caused the error.  The expression in which the
  2666.      error occurred will be evaluated a second time, so beware of
  2667.      side effects.
  2668.  
  2669.       dbret, value      -- continue execution by returning VALUE (which
  2670.                            may be nil or omitted) to the caller of the
  2671.                function in which the error occurred.
  2672.      This is useful if the function in which the error occurred is
  2673.      hopelessly confounded, but you know the value it should return.
  2674.  
  2675.    Yorick does not allow "single stepping" directly, although you can
  2676.    execute the statements in a function by copying them, then tell
  2677.    Yorick to skip those statements you have executed "by hand".  There
  2678.    are two functions for skipping execution:
  2679.  
  2680.       dbskip            -- skip the next logical line (This will be only
  2681.                            a portion of a source line if several statements
  2682.                are stacked on the source line.)
  2683.       dbskip, n         -- skip next N (positive or negative) logical lines
  2684.  
  2685.       dbup              -- discard the current function, so that you are
  2686.                            debugging its caller -- there is no way to go
  2687.                back "down", so be careful
  2688.  
  2689.    There are two functions which print information (like other print
  2690.    functions, if called as functions instead of subroutines, their
  2691.    result is returned as a string array with one line per string):
  2692.  
  2693.       dbinfo            -- returns current function and source line
  2694.  
  2695.       dbdis             -- returns disassembled virtual machine code
  2696.                            for the next line (use the disassemble function
  2697.                to get the entire function)
  2698.      This allows you to see exactly where in a line the error occurred.
  2699.  
  2700.    Finally,
  2701.  
  2702.       dbauto            -- toggles whether debug mode will be entered
  2703.                            automatically when a runtime error occurs
  2704.       dbauto, 1         -- enter debug mode automatically after an error
  2705.       dbauto, 0         -- type <RETURN> after error to enter debug mode
  2706.  */
  2707.  
  2708. /*--------------------------------------------------------------------------*/
  2709.  
  2710. extern _lst;
  2711. extern _cat;
  2712. extern _car;
  2713. extern _cdr;
  2714. extern _cpy;
  2715. extern _len;
  2716. /* DOCUMENT list= _lst(item1, item2, item3, ...)
  2717.             list= _cat(item_or_list1, item_or_list2, item_or_list3, ...)
  2718.         list= _cpy(list)
  2719.           list= _cpy(list, i)
  2720.         length= _len(list)
  2721.             item= _car(list)
  2722.               item_i= _car(list, i)
  2723.               _car, list, i, new_item_i
  2724.         list= _cdr(list)
  2725.           list= _cdr(list, i)
  2726.               _cdr, list, i, new_list_i
  2727.  
  2728.      implement rudimentary Lisp-like list handling in Yorick.
  2729.      However, in Yorick, a list must have a simple tree structure
  2730.      - no loops or rings are allowed (loops break Yorick's memory
  2731.      manager - beware).  You need to be careful not to do this as
  2732.      the error will not be detected.
  2733.  
  2734.      Lists are required in Yorick whenever you need to hold an
  2735.      indeterminate amount of non-array data, such as file handles,
  2736.      bookmarks, functions, index ranges, etc.  Note that Yorick
  2737.      pointers cannot point to these objects.  For array data, you have
  2738.      a choice between a list and a struct or an array of pointers.
  2739.      Note that a list cannot be written into a file with the save
  2740.      function, since it may contain unsaveable items.
  2741.  
  2742.      The _lst (list), _cat (catenate), and _cpy (copy) functions
  2743.      are the principal means for creating and maintaining lists.
  2744.      _lst makes a list out of its arguments, so that each argument
  2745.      becomes one item of the new list.  Unlike Yorick array data
  2746.      types, a statement like x=list does not make a copy of the
  2747.      list, it merely makes an additional reference to the list.
  2748.      You must explicitly use the _cpy function to copy a list.  Note
  2749.      that _cpy only copies the outermost list itself, not the items
  2750.      in the list (even if those items are lists).  With the second
  2751.      argument i, _cpy copies only the first i items in the list.
  2752.      The _cat function concatentates several lists together,
  2753.      "promoting" any arguments which are not lists.  This operation
  2754.      changes the values of list arguments to _cat, except for the
  2755.      final argument, since after _cat(list, item), the variable list
  2756.      will point to the new longer list returned by _cat.
  2757.  
  2758.      Nil, or [], functions as an empty list.  This leads to ambiguity
  2759.      in the argument list for _cat, since _cat "promotes" non-list
  2760.      arguments to lists; _cat treats [] as an empty list, not as a
  2761.      non-list item.  Also, _lst() or _lst([]) returns a single item list,
  2762.      not [] itself.
  2763.  
  2764.      The _len function returns the number of items in a list, or 0
  2765.      for [].
  2766.  
  2767.      The _car and _cdr functions (the names are taken from Lisp,
  2768.      where they originally stood for something like "address register"
  2769.      and "data register" of some long forgotten machine) provide
  2770.      access to the items stored in a list.  _car(list,i) returns the
  2771.      i-th item of the list, and i defaults to 1, so _car(list) is the
  2772.      first item.  Also, _car,list,i,new_item_i sets the i-th item
  2773.      of the list.  Finally, _cdr(list,i) returns a list of all the
  2774.      items beyond the i-th, where i again defaults to 1.  The form
  2775.      _cdr,list,i,new_list_i can be used to reset all list items
  2776.      beyond the i-th to new values.  In the _cdr function, i=0 is
  2777.      allowed.  When used to set values, both _car and _cdr can also
  2778.      be called as functions, in which case they return the item or
  2779.      list which has been replaced.  The _cdr(list) function returns
  2780.      nil if and only if LIST contains only a single item; this is
  2781.      the usual means of halting a loop over items in a list.
  2782.  
  2783.    SEE ALSO: array, grow, _prt, _map, _rev, _nxt
  2784.  */
  2785.  
  2786. func _prt(x, indent)
  2787. /* DOCUMENT _prt, list
  2788.      print every item in a list, recursing if some item is itself a list.
  2789.    SEE ALSO: _lst
  2790.  */
  2791. {
  2792.   if (is_void(indent)) indent= "";
  2793.   if (typeof(x)!="list") {
  2794.     write,format="%s\n",indent+print(x);
  2795.     return;                       /* exit recursion */
  2796.   }
  2797.   write,format="%s\n",indent+"list items:";
  2798.   do {
  2799.     _prt, _car(x), indent+"  ";   /* recurse */
  2800.     x= _cdr(x);
  2801.   } while (!is_void(x));
  2802. }
  2803.  
  2804. func _map(f__map, list__map)
  2805. /* DOCUMENT _map(f, list)
  2806.      return a list of the results of applying function F to each
  2807.      element of the input LIST in turn, as if by
  2808.        _lst(f(_car(list,1)),f(_car(list,2)),...)
  2809.    SEE ALSO: _lst
  2810.  */
  2811. {
  2812.   /* all locals here must have weird names, since the function f will
  2813.    * very often rely on external variables for arguments not varying
  2814.    * in the input list, or for accumulated outputs */
  2815.   if (is_void(list__map)) return [];
  2816.   result__map= tail__map= _lst(f__map(_car(list__map)));
  2817.   for (list__map=_cdr(list__map) ;
  2818.        !is_void(list__map) ; list__map=_cdr(list__map)) {
  2819.     _cat, tail__map, _lst(f__map(_car(list__map)));
  2820.     tail__map= _cdr(tail__map);
  2821.   }
  2822.   return result__map;
  2823. }
  2824.  
  2825. func _rev(list)
  2826. /* DOCUMENT _rev(list)
  2827.      returns the input list in reverse order
  2828.    SEE ALSO: _lst
  2829.  */
  2830. {
  2831.   if (is_void(list)) return;
  2832.   prev= [];
  2833.   for (;;) {
  2834.     tail= _cdr(list, 1, prev);
  2835.     if (is_void(tail)) return list;
  2836.     prev= list;
  2837.     list= tail;
  2838.   }
  2839. }
  2840.  
  2841. func _nxt(&list)
  2842. /* DOCUMENT item= _nxt(list)
  2843.      return first item in LIST, and set LIST to list of remaining
  2844.      items.  If you are iterating through a list, this is the way
  2845.      to do it, since a loop on _car(list,i) with i varying from 1
  2846.      to _len(list) scales quadratically with the length of the list,
  2847.      while a loop on _nxt(list) scales linearly.
  2848.    SEE ALSO: _car, _lst
  2849.  */
  2850. {
  2851.   item= _car(list);
  2852.   list= _cdr(list);
  2853.   return item;
  2854. }
  2855.  
  2856. /*--------------------------------------------------------------------------*/
  2857.